import React, { useEffect, useState } from "react";
import { useIntl } from "react-intl";
import Input from "./components/Input";
import { Button } from "./components/Button";
import { useQuery } from "@tanstack/react-query";
import {
  getBotByApiKey,
  getConfigs as wpGetConfigs,
  setConfigs as wpSetConfigs,
  updateConfigsMeta as wpUpdateConfigsMeta,
} from "./services/wordpress-api/shopinzen-integrator.service";
import { toast } from "react-toastify";
import { SwitchExample } from "./components/Switch";
import "../../index.css";
import "../../tailwind.css";
import "../register/register.css";
import { Loader } from "./components/Loader";
import { window_SHOPINZEN_INTEGRATOR_object } from "@src/dev-env";

const apiKeySample: any = "";
let tempPluginsExistingData: any = null;

const Home: React.FC<any> = () => {
  const intl = useIntl();

  return (
    <>
      {/* Hero Section - Nouveau Design (identique à register) */}
      <div className="shopinzen-hero">
        <div className="shopinzen-hero-overlay"></div>
        <div className="shopinzen-hero-content">
          <p className="shopinzen-hero-tag">
            {intl.formatMessage({
              defaultMessage: "100 % FREEMIUM – COMMENCEZ SANS PAYER",
              id: "hiPs8R",
            })}
          </p>
          <h1>
            {intl.formatMessage({
              defaultMessage:
                "Créez votre chatbot IA personnalisé pour votre site en quelques clics",
              id: "KEHqE0",
            })}
          </h1>
          <p className="shopinzen-hero-desc">
            {intl.formatMessage({
              defaultMessage:
                "ShopinZen rend votre site vivant : un chatbot intelligent qui guide vos visiteurs, booste vos conversions et révolutionne leur expérience, sans aucune ligne de code.",
              id: "aSMbeE",
            })}
          </p>
          <div className="shopinzen-hero-buttons">
            <a
              href={`${window_SHOPINZEN_INTEGRATOR_object.getKey("dashboard_url")}/auth/login`}
              className="shopinzen-btn-hero-primary"
              target="_blank"
              rel="noopener noreferrer"
            >
              {intl.formatMessage({
                defaultMessage: "Démarrer l'essai gratuit",
                id: "YDSE04",
              })}
            </a>

            <a
              href={`${window_SHOPINZEN_INTEGRATOR_object.getKey("dashboard_url")}`}
              className="shopinzen-btn-hero-secondary"
              target="_blank"
              rel="noopener noreferrer"
            >
              {intl.formatMessage({
                defaultMessage: "Essayer la démo",
                id: "q2E2cb",
              })}
            </a>
          </div>
        </div>
      </div>
      <InputSection />
    </>
  );
};

const InputSection: React.FC<any> = () => {
  const intl = useIntl();

  const [apiKey, setApiKey] = useState<any>(apiKeySample);
  const [isLoadingPluginsExistingData, setIsLoadingPluginsExistingData] =
    useState<any>(false);
  const [pluginsExistingData, setPluginsExistingData] = useState<any>(null);
  const [newBot, setNewBot] = useState<any>(null);
  const [showApiKeyForm, setShowApiKeyForm] = useState<any>(false);

  const onApiKeyInputSubmit = () => {
    refecthGetBotByApiKey();
    if (!apiKey) return;
  };

  const getConfigs = async () => {
    setIsLoadingPluginsExistingData(true);

    await wpGetConfigs()
      .then((res: any) => {
        setIsLoadingPluginsExistingData(false);

        if (res && res.data !== "") {
          setPluginsExistingData(res.data);
          setShowApiKeyForm(false);
          return res.data;
        }

        setShowApiKeyForm(true);
        return null;
      })
      .catch(() => {
        setIsLoadingPluginsExistingData(false);
      });
  };

  const {
    data,
    isFetching: isCheckingApiKey,
    error: error_apiKey,
    refetch: refecthGetBotByApiKey,
  }: any = useQuery(["bot", { apiKey }], getBotByApiKey as any, {
    enabled: false,
    retry: false,
  });

  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
    getConfigs();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [(window as any).location]);

  useEffect(() => {
    if (error_apiKey) {
      toast.error(error_apiKey.message, {
        hideProgressBar: true,
        position: "bottom-right",
      });
    }
  }, [error_apiKey]);

  useEffect(() => {
    if (data) {
      setShowApiKeyForm(false);
      setNewBot(data?.data);
    }
  }, [data]);

  useEffect(() => {
    setShowApiKeyForm(!pluginsExistingData);
  }, [pluginsExistingData]);

  return (
    <section className="min-h-[200px] bg-gray-50 p-10">
      {isLoadingPluginsExistingData && (
        <div className="flex flex-col items-center justify-center py-20 animate-fade-in">
          <Loader radius={40} color="currentColor" />
          <p className="mt-4 text-gray-500 font-medium">
            {intl.formatMessage({
              defaultMessage: "Chargement en cours, veuillez patienter...",
              id: "Degbc8",
            })}
          </p>
        </div>
      )}

      {!isLoadingPluginsExistingData &&
        !showApiKeyForm &&
        (pluginsExistingData || newBot) && (
          <>
            <DisplayWidgetSwitch
              checked={pluginsExistingData?.meta?.canDisplayWidget}
              pluginData={pluginsExistingData}
            />

            <div className="mb-2 text-right">
              <button
                className="my-0 text-blue-600 underline"
                onClick={() => {
                  setShowApiKeyForm(true);
                  tempPluginsExistingData = pluginsExistingData;
                  setPluginsExistingData(null);
                }}
              >
                {intl.formatMessage({
                  defaultMessage: "Saisir une clé d'API",
                  id: "2yanaI",
                })}
              </button>
            </div>

            <BotSection
              setPluginConfigsCallback={(data: any) => setPluginsExistingData(data)}
              public_key={apiKey}
              newBot={newBot}
              pluginsExistingData={pluginsExistingData}
            />
          </>
        )}

      {!isLoadingPluginsExistingData &&
        showApiKeyForm &&
        !pluginsExistingData && (
          <div className="h-full grid items-center">
            <div className="flex items-center justify-end">
              <button
                className="my-0 rounded-none text-red-500 bg-none border-red-500"
                onClick={() => {
                  setPluginsExistingData(tempPluginsExistingData);
                  setShowApiKeyForm(false);
                  tempPluginsExistingData = null;
                }}
              >
                {intl.formatMessage({ defaultMessage: "Fermer", id: "yRDVX2" })}
              </button>
            </div>

            <div className="input gap-1 w-full px-10">
              <Input
                type="password"
                onChange={(e: any) => setApiKey(e.target.value)}
                label={intl.formatMessage({
                  defaultMessage: "Entrez votre clé API pour ajouter ShopinZen",
                  id: "AX3zeH",
                })}
                variant="outline"
                value={apiKey}
                className="mb-5"
                disabled={isCheckingApiKey}
              />

              <div className="w-full text-center">
                <Button
                  disabled={!apiKey}
                  className="my-0"
                  isLoading={isCheckingApiKey}
                  onClick={onApiKeyInputSubmit}
                >
                  {intl.formatMessage({
                    defaultMessage: "Valider",
                    id: "L3I+Rg",
                  })}
                </Button>
              </div>
            </div>
          </div>
        )}
    </section>
  );
};

const DisplayWidgetSwitch: React.FC<any> = ({
  checked: isChecked,
  pluginData,
  onChange = () => {},
}) => {
  const intl = useIntl();

  const [checked, setChecked] = useState<any>(false);
  const [isLoading, setIsLoading] = useState<any>(false);

  const onDisplaySwitchChange = (value: any) => {
    if (isLoading) return;
    setIsLoading(true);

    const loadingToast = toast.info(
      intl.formatMessage({
        defaultMessage: "Veuillez patienter",
        id: "TKPr1i",
      }),
      {
        isLoading: true,
        position: "bottom-right",
        closeButton: false,
        closeOnClick: false,
        toastId: "loadingToast",
      },
    );

    wpUpdateConfigsMeta({
      ...(pluginData?.meta || {}),
      canDisplayWidget: value,
    })
      .then(() => {
        setChecked(value);
        onChange(value);

        toast.update(loadingToast, {
          render: intl.formatMessage({
            defaultMessage: "Mise à jour effectuée !",
            id: "znKChk",
          }),
          isLoading: false,
          type: "success",
          autoClose: null,
          closeOnClick: true,
        });

        setIsLoading(false);
      })
      .catch((error: any) => {
        toast.update(loadingToast, {
          render:
            error.message ||
            intl.formatMessage({
              defaultMessage: "Une erreur est survenue",
              id: "uM26tE",
            }),
          isLoading: false,
          type: "error",
          autoClose: null,
          closeOnClick: true,
        });

        setIsLoading(false);
      });
  };

  useEffect(() => {
    setChecked(isChecked);
  }, [isChecked]);

  return (
    <div className="my-2 text-right">
      <SwitchExample
        label={intl.formatMessage({
          defaultMessage: "Afficher le chatbot sur le site",
          id: "j0QJfq",
        })}
        className="my-0"
        onChange={onDisplaySwitchChange}
        checked={checked}
        disabled={isLoading}
      />
    </div>
  );
};

 const BotSection: React.FC<any> = ({
  newBot,
  public_key,
  pluginsExistingData,
  setPluginConfigsCallback = () => {},
}) => {
  const intl = useIntl();

  const [isActivated, setIsActivated] = useState<any>(false);
  const [isLoading, setIsLoading] = useState<any>(false);
  const [pluginConfigs, setPluginConfigs] = useState<any>(null);

  const api_setPluginConfigs = (configs: any) => {
    if (!configs) return;

    setIsLoading(true);

    return wpSetConfigs(configs)
      .then((res: any) => {
        setIsLoading(false);
        setIsActivated(true);

        if (res && res.data !== "") {
          toast.success(
            intl.formatMessage({
              defaultMessage: "Activation réussie !",
              id: "R+MWXj",
            }),
            {
              hideProgressBar: true,
              position: "bottom-right",
            },
          );

          setPluginConfigsCallback(res.data);
        }

        return res?.data;
      })
      .catch((error: any) => {
        setIsLoading(false);

        toast.error(
          error.message ||
            error.response?.data?.message ||
            intl.formatMessage({
              defaultMessage: "Une erreur est survenue",
              id: "uM26tE",
            }),
          {
            hideProgressBar: true,
            position: "bottom-right",
          },
        );
      });
  };

  const bot = newBot || pluginsExistingData?.chatbot;

  useEffect(() => {
    if (bot) {
      setPluginConfigs({
        public_key,
        chatbot: { ...bot },
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bot]);

  return (
    <div>
      {bot && (
        <>
          <div className="rounded-sm p-2">
            <h1 className="leading-normal font-bold text-xl mb-4">
              {intl.formatMessage({
                defaultMessage: "Informations sur le bot",
                id: "QhuUIO",
              })}
            </h1>

            <p>
              <strong>
                {intl.formatMessage({ defaultMessage: "Nom", id: "h4Insz" })}:
              </strong>{" "}
              {bot.botName}
            </p>
          </div>
          {!isActivated && newBot && (
            <Button
              className="my-0"
              isLoading={isLoading}
              onClick={() =>
                api_setPluginConfigs({
                  ...pluginConfigs,
                  chatbot: JSON.stringify(pluginConfigs?.chatbot),
                  meta: JSON.stringify(
                    pluginConfigs?.meta || { canDisplayWidget: true },
                  ),
                }) as any
              }
            >
              {intl.formatMessage(
                {
                  defaultMessage: "Intégrer {botName} sur ce site",
                  id: "xZAbW4",
                },
                { botName: bot.botName },
              )}
            </Button>
          )}
        </>
      )}
    </div>
  );
};

export default Home;
