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 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 { 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.emailConfirm(),
  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 activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const { subPlan } = useParams();
  const { error, isLoading, authorization } = useAuthentication();
  // const { products } = usePaywall({
  //   placementKey: EPlacementKeys["aura.placement.main"],
  // });
  const { products } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const [activeProduct, setActiveProduct] = useState<IFunnelPaymentVariant | 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, [
    //   EMetrics.KLAVIYO,
    //   EMetrics.YANDEX,
    //   EMetrics.FACEBOOK,
    // ]);
  };

  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"]}>{translate("we_dont_share")}</p>
      <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)}
      />
      <Policy sizing="medium" 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>
      <MainButton
        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.webp"
            alt="Success Icon"
          />
        )}
      </MainButton>
      {!!error?.length && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          Something went wrong
        </Title>
      )}
    </section>
  );
}

export default EmailEnterPage;
