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, useSearchParams } from "react-router-dom";
import { useEffect, useMemo, useState } from "react";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { actions, selectors } from "@/store";
import { ELottieKeys, useLottie } from "@/hooks/lottie/useLottie";
import Title from "@/components/Title";
import EmailInput from "../ABDesign/v1/pages/EmailEnterPage/EmailInput";
import Loader, { LoaderColor } from "@/components/Loader";
import Policy from "@/components/Policy";
import PasswordInput from "../ABDesign/v1/pages/EmailEnterPage/PasswordInput";
import ResetYourPassword from "./ResetYourPassword";
import Toast from "../ABDesign/v1/components/Toast";
import { Password } from "@/api";
import Header from "@/components/CompatibilityV2/components/Header";
import Button from "@/components/CompatibilityV2/components/Button";
import { IFunnelPaymentVariant } from "@/api/resources/Session";
import { useFunnel } from "@/hooks/funnel/useFunnel";

interface IAuthPage {
  redirectUrl?: string;
}

function Auth({ redirectUrl: propRedirectUrl = routes.client.home() }: IAuthPage) {
  // Get redirectUrl from URL query parameters if present, otherwise use the prop value
  const [searchParams] = useSearchParams();
  const redirectUrlFromQuery = searchParams.get('redirectUrl');
  const redirectUrl = redirectUrlFromQuery || propRedirectUrl;
  const [passwordFromQuery, emailFromQuery] = useMemo(() => {
    const url = window.location.href;
    const [_password, _email] = url.split("?")?.[1]?.split("password=", 2)?.[1]?.split("&email=") || ["", ""]
    return [decodeURIComponent(_password?.split("&")?.[0]), decodeURIComponent(_email?.split("&")?.[0])]
  }, [window.location.href]);

  const { translate } = useTranslations(ELocalesPlacement.V1);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [email, setEmail] = useState(emailFromQuery || "");
  const [password, setPassword] = useState(passwordFromQuery || "");
  const [isDisabled, setIsDisabled] = useState(true);
  const [isValidEmail, setIsValidEmail] = useState(false);
  const [isValidPassword, setIsValidPassword] = useState(false);
  const [isAuth, setIsAuth] = useState(false);
  const { subPlan } = useParams();
  const { error, isLoading, token, user, authorizationWithPassword } =
    useAuthentication();
  const activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const { products } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const [activeProduct, setActiveProduct] = useState<IFunnelPaymentVariant | 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]);

  useEffect(() => {
    if (emailFromQuery?.length) {
      setIsValidEmail(true);
    }
    if (passwordFromQuery?.length) {
      setIsValidPassword(true);
    }
  }, [emailFromQuery, passwordFromQuery]);


  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(() => {
        // Use window.location.href for a full page reload to ensure server-side redirects work
        // This is especially important when redirecting from the auth page
        window.location.href = 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`}
    >
      <Header
        className={styles.header}
        classNameTitle={styles["header-title"]}
        isBackButtonVisible={false}
      />
      <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")}
        inputClassName={styles.input}
        onValid={handleValidEmail}
        onInvalid={() => setIsValidEmail(false)}
      />
      <PasswordInput
        value={password}
        placeholder={"Password"}
        inputClassName={styles.input}
        onValid={handleValidPassword}
        onInvalid={() => setIsValidPassword(false)}
      />
      <Button
        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"
          />
        )}
      </Button>
      <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;
