import styles from "./styles.module.css";
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import Title from "../Title";
import Policy from "../Policy";
import EmailInput from "./EmailInput";
import MainButton from "../MainButton";
import Loader, { LoaderColor } from "../Loader";
import routes from "@/routes";
import NameInput from "./NameInput";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ESourceAuthorization } from "@/api/resources/User";
import { EPlacementKeys, IPaywallProduct } from "@/api/resources/Paywall";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import metricService, { EGoals } from "@/services/metric/metricService";

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

function EmailEnterPage({
  redirectUrl = routes.client.emailConfirm(),
  isRequiredName = false,
}: IEmailEnterPage): JSX.Element {
  const { t } = useTranslation();
  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 activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const { subPlan } = useParams();
  const { error, isLoading, authorization } = useAuthentication();
  const { products } = usePaywall({
    placementKey: EPlacementKeys["aura.placement.main"],
  });
  const [activeProduct, setActiveProduct] = useState<IPaywallProduct | null>(
    activeProductFromStore
  );

  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);
  };

  const authorize = async () => {
    let source = ESourceAuthorization["aura.main"];
    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);
    dispatch(
      actions.payment.update({
        activeProduct,
      })
    );
    setIsAuth(true);
    setTimeout(() => {
      navigate(redirectUrl);
    }, 1000);
  };

  return (
    <section className="page">
      <Title variant="h2" className={styles.title}>
        Enter your email
      </Title>
      <p className={styles["not-share"]}>{t("we_dont_share")}</p>
      <EmailInput
        name="email"
        value={email}
        placeholder={t("your_email")}
        onValid={handleValidEmail}
        onInvalid={() => setIsValidEmail(false)}
      />
      <NameInput
          value={name}
          placeholder="Your name"
          onValid={handleValidName}
          onInvalid={() => setIsValidName(!isRequiredName)}
      />
      <Policy sizing="medium" className={styles.policy}>
        {t("_continue_agree", {
          eulaLink: (
            <a
              className={styles.link}
              href="https://aura.wit.life/terms"
              target="_blank"
              rel="noopener noreferrer"
            >
              {t("eula")}
            </a>
          ),
          privacyLink: (
            <a
              className={styles.link}
              href="https://aura.wit.life/privacy"
              target="_blank"
              rel="noopener noreferrer"
            >
              {t("privacy_policy")}
            </a>
          ),
        })}
      </Policy>
      <MainButton
        className={styles.button}
        onClick={handleClick}
        disabled={isDisabled}
      >
        {isLoading && <Loader color={LoaderColor.White} />}
        {!isLoading &&
          !(!error?.length && !isLoading && isAuth) &&
          t("_continue")}
        {!error?.length && !isLoading && isAuth && (
          <img
            className={styles["success-icon"]}
            src="/SuccessIcon.png"
            alt="Success Icon"
          />
        )}
      </MainButton>
      {!!error?.length && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          Something went wrong
        </Title>
      )}
    </section>
  );
}

export default EmailEnterPage;
