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 Title from "@/components/Title";
import Policy from "@/components/Policy";
import Loader, { LoaderColor } from "@/components/Loader";
import { ESourceAuthorization } from "@/api/resources/User";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ELottieKeys, useLottie } from "@/hooks/lottie/useLottie";
import ButtonBack from "../../components/ButtonBack";
import { Button } from "../../ui/Button";
import { useGenderInfo } from "../../lib/getGenderInfo";
import { useStyle } from "@/routerComponents/Mike/v1/providers/StyleProvider/useStyle";
import { Message } from "../../components/Message";
import EmailInput from "@/components/EmailEnterPage/EmailInput";
import NameInput from "@/components/EmailEnterPage/NameInput";
import { IFunnelPaymentVariant } from "@/api/resources/Session";
import { useFunnel } from "@/hooks/funnel/useFunnel";
import { ELocalesPlacement } from "@/locales";

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

function EmailEnterPage({
  redirectUrl = routes.client.mikeV1() + routes.client.trialPayment(),
  isRequiredName = false,
}: IEmailEnterPage): JSX.Element {
  const { translate } = useTranslations();
  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 { error, isLoading, token, user, authorization } = useAuthentication();
  const { setStyle } = useStyle();
  const infoGender = useGenderInfo();
  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 = () => {
    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);
      const timeout = setTimeout(() => {
        navigate(redirectUrl);
      }, 1000);
      return () => {
        clearTimeout(timeout);
      };
    }
  }, [
    activeProduct,
    dispatch,
    error,
    isLoading,
    navigate,
    redirectUrl,
    token?.length,
    user,
  ]);

  useEffect(() => {
    if (infoGender) {
      setStyle({
        backgroundColor: "#F7F7F7",
        backgroundImage: `url(/mike/bg-gradient-${infoGender.id}.webp)`,
        backgroundPosition: "bottom",
        backgroundRepeat: "no-repeat",
      });
    }
  }, [infoGender, setStyle]);

  useEffect(() => {
    dispatch(actions.privacyPolicy.updateChecked(true));
    setActiveProduct(products[0]);
  }, [activeProduct, dispatch, products]);

  return (
    <div className="page-mike">
      <ButtonBack />
      <div className={styles["avatar-content"]}>
        <img src="/mike/avatar_3.webp" />
        <Message>{translate("mike.emailEnter.message")}</Message>
        <p className={styles["not-share"]}>{translate("we_dont_share")}</p>
      </div>
      <div className={styles.form}>
        <EmailInput
          name="email"
          value={email}
          placeholder={translate("your_email")}
          onValid={handleValidEmail}
          onInvalid={() => setIsValidEmail(false)}
        />
        <NameInput
          value={name}
          placeholder="Your name"
          onValid={handleValidName}
          onInvalid={() => setIsValidName(!isRequiredName)}
        />
        <Button
          className={styles.button}
          onClick={handleClick}
          disabled={isDisabled}
          style={{ backgroundColor: infoGender?.colorAssociation }}
        >
          {isLoading && <Loader color={LoaderColor.White} />}
          {!isLoading && !(!error?.length && !isLoading && isAuth) && translate("next")}
          {!error?.length && !isLoading && isAuth && (
            <img
              className={styles["success-icon"]}
              src="/SuccessIcon-white.svg"
              alt="Success Icon"
            />
          )}
        </Button>
        <Policy sizing="large" className={styles.policy}>
          {translate("_continue_agree", {
            eulaLink: (
              <a
                className={styles.link}
                href="https://aura.wit.life/terms"
                target="_blank"
                rel="noopener noreferrer"
              >
                {translate("eula")}
              </a>
            ),
            privacyLink: (
              <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>
        )}
      </div>
    </div>
  );
}

export default EmailEnterPage;
