import styles from "./styles.module.css";
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslations } from "@/hooks/translations";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import routes from "@/routes";
import NameInput from "./NameInput";
import Title from "@/components/Title";
import EmailInput from "./EmailInput";
import Policy from "@/components/Policy";
import Loader, { LoaderColor } from "@/components/Loader";
import Header from "../../components/Header";
import BackgroundTopBlob from "../../ui/BackgroundTopBlob";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import QuestionnaireGreenButton from "../../ui/GreenButton";
import { ESourceAuthorization } from "@/api/resources/User";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ELottieKeys, useLottie } from "@/hooks/lottie/useLottie";
import { ELocalesPlacement } from "@/locales";
import { useSession } from "@/hooks/session/useSession";
import { IFunnelPaymentVariant } from "@/api/resources/Session";
import { useFunnel } from "@/hooks/funnel/useFunnel";

interface IEmailEnterPage {
  redirectUrl?: string;
  isRequiredName?: boolean;
}

function EmailEnterPage({
  redirectUrl = routes.client.emailConfirmV1(),
  isRequiredName = false,
}: IEmailEnterPage): JSX.Element {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const { updateSession } = useSession();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [isDisabled, setIsDisabled] = useState(true);
  const [isValidEmail, setIsValidEmail] = useState(false);
  const [isValidName, setIsValidName] = useState(!isRequiredName);
  const [isAuth, setIsAuth] = useState(false);
  const { subPlan } = useParams();
  const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
  const { error, isLoading, token, user, authorization } = useAuthentication();
  const { gender } = useSelector(selectors.selectQuestionnaire);
  const activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const { products } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const [activeProduct, setActiveProduct] = useState<IFunnelPaymentVariant | null>(
    activeProductFromStore
  );

  useLottie({
    preloadKey: ELottieKeys.handWithStars,
  });

  useEffect(() => {
    if (subPlan) {
      const targetProduct = products.find(
        (product) =>
          String(
            product?.trialPrice
              ? Math.floor((product?.trialPrice + 1) / 100)
              : product.key.replace(".", "")
          ) === subPlan
      );
      if (targetProduct) {
        setActiveProduct(targetProduct);
      }
    }
  }, [subPlan, products]);

  const handleValidEmail = (email: string) => {
    dispatch(actions.form.addEmail(email));
    setEmail(email);
    setIsValidEmail(true);
  };

  const handleValidName = (name: string) => {
    if (name) {
      dispatch(
        actions.user.update({
          username: name,
        })
      );
    }
    setName(name);
    setIsValidName(true);
  };

  useEffect(() => {
    if (isValidName && isValidEmail) {
      setIsDisabled(false);
    } else {
      setIsDisabled(true);
    }
  }, [isValidEmail, isValidName, email, name]);

  const handleClick = async () => {
    if (name.length) {
      await updateSession(
        {
          profile: {
            name,
          },
        },
        ESourceAuthorization["aura.main.new"]
      );
    }
    authorize();
    // metricService.reachGoal(EGoals.ENTERED_EMAIL, [
    //   EMetrics.KLAVIYO,
    //   EMetrics.YANDEX,
    //   EMetrics.FACEBOOK,
    // ]);
  };

  const authorize = async () => {
    let source = ESourceAuthorization["aura.main.new"];
    if (window.location.pathname.includes("advisor-chat")) {
      source = ESourceAuthorization["aura.chat"];
    }
    if (window.location.pathname.includes("/epe/")) {
      source = ESourceAuthorization["aura.moons"];
    }
    await authorization(email, source);
  };

  useEffect(() => {
    if (user && token?.length && !isLoading && !error) {
      dispatch(
        actions.payment.update({
          activeProduct,
        })
      );
      setIsAuth(true);
      dispatch(actions.paywalls.resetIsMustUpdate());
      const timeout = setTimeout(() => {
        navigate(redirectUrl);
      }, 1000);
      return () => {
        clearTimeout(timeout);
      };
    }
  }, [
    activeProduct,
    dispatch,
    error,
    isLoading,
    navigate,
    redirectUrl,
    token?.length,
    user,
  ]);

  return (
    <section
      className={`${styles.page} page`}
      ref={pageRef}
      style={{ backgroundColor: gender === "male" ? "#C1E5FF" : "#f7ebff" }}
    >
      <BackgroundTopBlob
        width={pageWidth}
        className={styles["background-top-blob"]}
        height={180}
      />
      <Header className={styles.header} />
      <Title variant="h2" className={styles.title}>
        {translate("/email.title")}
      </Title>
      <p className={styles["not-share"]}>{translate("/email.description")}</p>
      <EmailInput
        name="email"
        value={email}
        placeholder={translate("/email.placeholder_email")}
        onValid={handleValidEmail}
        onInvalid={() => setIsValidEmail(false)}
      />
      <NameInput
        value={name}
        placeholder={translate("/email.placeholder_name")}
        onValid={handleValidName}
        onInvalid={() => setIsValidName(!isRequiredName)}
      />
      <QuestionnaireGreenButton
        className={styles.button}
        onClick={handleClick}
        disabled={isDisabled}
      >
        {isLoading && <Loader color={LoaderColor.White} />}
        {!isLoading &&
          !(!error?.length && !isLoading && isAuth) &&
          translate("continue")}
        {!error?.length && !isLoading && isAuth && (
          <img
            className={styles["success-icon"]}
            src="/SuccessIcon-white.svg"
            alt="Success Icon"
          />
        )}
      </QuestionnaireGreenButton>
      <Policy sizing="medium" className={styles.policy}>
        {translate("/email.policy", {
          eulaLink: (
            <a
              className={styles.link}
              href="https://aura.wit.life/terms"
              target="_blank"
              rel="noopener noreferrer"
            >
              {translate("/email.policy_eula")}
            </a>
          ),
          privacyPolicy: (
            <a
              className={styles.link}
              href="https://aura.wit.life/privacy"
              target="_blank"
              rel="noopener noreferrer"
            >
              {translate("privacy_policy")}
            </a>
          ),
        })}
      </Policy>
      {!!error?.length && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          Something went wrong
        </Title>
      )}
    </section>
  );
}

export default EmailEnterPage;
