import { useTranslation } from "react-i18next";
import { useAuth } from "../auth/Auth";
import { useConfig } from "../config/ConfigProvider";
import { WidgetHelper } from "./widget-helper";

/**
 * Hook that opens the feedback widget
 */
export const useMessagesWidget = () => {
  const { t } = useTranslation();
  const { user } = useAuth();
  const { config } = useConfig();

  const apiUrl = config?.FRONTEND_FEEDBACK_MESSAGES_WIDGET_API_URL;
  const widgetPath = config?.FRONTEND_FEEDBACK_MESSAGES_WIDGET_PATH;
  const channel = config?.FRONTEND_FEEDBACK_MESSAGES_WIDGET_CHANNEL;

  const getWidgetConfig = () => {
    const title: string = t("feedback_widget.title");
    const placeholder: string = t("feedback_widget.placeholder");
    const emailPlaceholder: string = t("feedback_widget.email_placeholder");
    const submitText: string = t("feedback_widget.submit_text");
    const successText: string = t("feedback_widget.success_text");
    const successText2: string = t("feedback_widget.success_text2");
    return {
      title,
      placeholder,
      emailPlaceholder,
      submitText,
      successText,
      successText2,
    };
  };

  const canLoadWidget = Boolean(channel && apiUrl && widgetPath);

  const showWidget = () => {
    if (!canLoadWidget) {
      throw new Error(
        "FRONTEND_FEEDBACK_MESSAGES_WIDGET_API_URL, FRONTEND_FEEDBACK_MESSAGES_WIDGET_PATH or FRONTEND_FEEDBACK_MESSAGES_WIDGET_CHANNEL is not set",
      );
    }

    WidgetHelper.pushCommand([
      "feedback",
      "init",
      {
        api: apiUrl,
        channel,
        ...getWidgetConfig(),
        // Add email parameter if user is logged in
        ...(user?.email && { email: user.email }),
      },
    ]);

    WidgetHelper.loadScript(`${widgetPath}feedback.js`);
  };

  const showButton = () => {
    if (!canLoadWidget) {
      throw new Error(
        "FRONTEND_FEEDBACK_MESSAGES_WIDGET_API_URL, FRONTEND_FEEDBACK_MESSAGES_WIDGET_PATH or FRONTEND_FEEDBACK_MESSAGES_WIDGET_CHANNEL is not set",
      );
    }

    WidgetHelper.pushCommand([
      "loader",
      "init",
      {
        params: {
          api: apiUrl,
          channel,
          ...getWidgetConfig(),
          // Add email parameter if user is logged in
          ...(user?.email && { email: user.email }),
        },
        script: `${widgetPath}feedback.js`,
      },
    ]);

    WidgetHelper.loadScript(`${widgetPath}loader.js`);
  };

  return { showWidget, showButton, canLoadWidget };
};
