import routes from "@/routes";
import styles from "./styles.module.scss";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { actions, selectors } from "@/store";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
import { ELottieKeys, useLottie } from "@/hooks/lottie/useLottie";
import metricService, {
  EGoals,
  EMetrics,
} from "@/services/metric/metricService";
import BackgroundTopBlob from "../ABDesign/v1/ui/BackgroundTopBlob";
import Title from "@/components/Title";
import EmailInput from "../ABDesign/v1/pages/EmailEnterPage/EmailInput";
import QuestionnaireGreenButton from "../ABDesign/v1/ui/GreenButton";
import Loader, { LoaderColor } from "@/components/Loader";
import Policy from "@/components/Policy";
import Header from "../ABDesign/v1/components/Header";
import PasswordInput from "../ABDesign/v1/pages/EmailEnterPage/PasswordInput";
import ResetYourPassword from "./ResetYourPassword";
import Toast from "../ABDesign/v1/components/Toast";
import { Password } from "@/api";

interface IAuthPage {
  redirectUrl?: string;
}

function Auth({ redirectUrl = routes.client.home() }: IAuthPage) {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isDisabled, setIsDisabled] = useState(true);
  const [isValidEmail, setIsValidEmail] = useState(false);
  const [isValidPassword, setIsValidPassword] = useState(false);
  const [isAuth, setIsAuth] = useState(false);
  const { subPlan } = useParams();
  const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
  const { error, isLoading, token, user, authorizationWithPassword } =
    useAuthentication();
  const { gender } = useSelector(selectors.selectQuestionnaire);
  const activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const { products } = usePaywall({
    placementKey: EPlacementKeys["aura.placement.redesign.main"],
    localesPlacement: ELocalesPlacement.V1,
  });
  const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
    activeProductFromStore
  );
  const [toastText, setToastText] = useState("");
  const [resultResetPassword, setResultResetPassword] =
    useState<Password.Response>();

  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 handleValidPassword = (password: string) => {
    // if (password) {
    //   dispatch(
    //     actions.user.update({
    //       password,
    //     })
    //   );
    // }
    setPassword(password);
    setIsValidPassword(true);
  };

  useEffect(() => {
    setToastText("");
    if (isValidPassword && isValidEmail) {
      setIsDisabled(false);
    } else {
      setIsDisabled(true);
    }
  }, [isValidEmail, email, password, isValidPassword]);

  const handleClick = async () => {
    authorize();
    metricService.reachGoal(EGoals.ENTERED_EMAIL, [
      EMetrics.KLAVIYO,
      EMetrics.YANDEX,
      EMetrics.FACEBOOK,
    ]);
  };

  const authorize = async () => {
    const result = await authorizationWithPassword(email, password);
    if (!!result && "message" in result && result?.message?.length) {
      setToastText(result.message);
    }
  };

  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,
  ]);

  useEffect(() => {
    if (resultResetPassword && resultResetPassword.message) {
      setToastText(resultResetPassword.message);
    }
  }, [resultResetPassword]);

  const handleClickResetPassword = () => {
    setToastText("Wrong email");
  };

  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)}
      />
      <PasswordInput
        value={password}
        placeholder={"Password"}
        onValid={handleValidPassword}
        onInvalid={() => setIsValidPassword(false)}
      />
      <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>
      <ResetYourPassword
        email={email}
        setResultResetPassword={setResultResetPassword}
        onClick={!isValidEmail ? handleClickResetPassword : undefined}
      />
      <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>
      )} */}
      {!!toastText && (
        <Toast classNameContainer={styles["toast-container"]} variant="error">
          <span className={styles["toast-text"]}>{toastText}</span>
        </Toast>
      )}
    </section>
  );
}

export default Auth;
