import Title from "@/components/Title";
import styles from "./styles.module.scss";
import EmailInput from "@/components/pages/ABDesign/v1/pages/EmailEnterPage/EmailInput";
import { useCallback, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import Button from "../../components/Button";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ESourceAuthorization } from "@/api/resources/User";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import Loader, { LoaderColor } from "@/components/Loader";
import Policy from "@/components/Policy";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import {
  useMetricABFlags,
} from "@/services/metric/metricService";
import NameInput from "@/components/pages/ABDesign/v1/pages/EmailEnterPage/NameInput";
import { useSession } from "@/hooks/session/useSession";

function Email() {
  const { updateSession } = useSession();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { error, isLoading, token, user, authorization } = useAuthentication();
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV1);

  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [isValidEmail, setIsValidEmail] = useState(false);
  const [isValidName, setIsValidName] = useState(true);
  const [isDisabled, setIsDisabled] = useState(true);
  const [isAuth, setIsAuth] = useState(false);

  const { flags } = useMetricABFlags();
  const auraVideoTrial = flags?.auraVideoTrial?.[0];

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

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

  const authorize = async () => {
    updateSession(
      {
        profile: {
          name,
        },
      },
      ESourceAuthorization["aura.palmistry.new"]
    );
    // metricService.reachGoal(EGoals.LEAD, [EMetrics.FACEBOOK]);
    // metricService.reachGoal(EGoals.ENTERED_EMAIL, [
    //   EMetrics.KLAVIYO,
    //   EMetrics.YANDEX,
    //   EMetrics.FACEBOOK,
    // ]);
    // metricService.reachGoal(EGoals.ENTERED_EMAIL_PALMISTRY, [EMetrics.YANDEX]);
    await authorization(email, ESourceAuthorization["aura.palmistry.new"]);
  };

  const handleNext = useCallback(() => {
    if (auraVideoTrial === "on") {
      return navigate(routes.client.palmistryV1TrialChoiceVideo());
    }
    return navigate(routes.client.palmistryV1TrialChoice());
  }, [auraVideoTrial, navigate]);

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

  return (
    <>
      <Title variant="h2" className={styles.title}>
        {translate("/email.title")}
      </Title>
      <EmailInput
        name="email"
        value={email}
        placeholder={translate("/email.placeholder_email")}
        placeholderClassName={styles["input-placeholder"]}
        inputClassName={styles.input}
        onValid={handleValidEmail}
        onInvalid={() => setIsValidEmail(false)}
      />
      <NameInput
        value={name}
        placeholder={translate("/email.placeholder_name")}
        inputClassName={styles.input}
        placeholderClassName={styles["input-placeholder"]}
        onValid={handleValidName}
        onInvalid={() => setIsValidName(true)}
      />
      <p className={styles["not-share"]}>{translate("/email.not_share")}</p>
      <Button
        className={styles.button}
        onClick={handleClick}
        disabled={isDisabled}
      >
        {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="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",
                  undefined,
                  ELocalesPlacement.V1
                )}
              </a>
            ),
            privacyPolicy: (
              <a
                className={styles.link}
                href="https://aura.wit.life/privacy"
                target="_blank"
                rel="noopener noreferrer"
              >
                {translate("privacy_policy", undefined, ELocalesPlacement.V1)}
              </a>
            ),
          },
          ELocalesPlacement.V1
        )}
      </Policy>
      {!!error?.length && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          {translate("went_wrong", undefined, ELocalesPlacement.PalmistryV1)}
        </Title>
      )}
    </>
  );
}

export default Email;
