import React from "react";
import { useTranslations } from "@/hooks/translations";
import { useDispatch, useSelector } from "react-redux";
import useSteps from "@/hooks/palmistry/use-steps";
import Button from "@/components/palmistry/button/button";
import Input from "@/components/palmistry/input/input";
import { actions, selectors } from "@/store";
import Title from "@/components/Title";
import Loader, { LoaderColor } from "@/components/Loader";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ESourceAuthorization } from "@/api/resources/User";
import { useSession } from "@/hooks/session/useSession";
import { ELocalesPlacement } from "@/locales";

const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;

export default function StepEmail() {
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV0);
  const dispatch = useDispatch();
  const { updateSession } = useSession();

  const steps = useSteps();

  const [email, setEmail] = React.useState(steps.storedValue);
  const storedName =
    useSelector(selectors.selectUser)?.profile?.full_name || "";
  const [name, setName] = React.useState(storedName);
  const [emailIsValid, setEmailIsValid] = React.useState(false);
  const [nameIsValid, setNameIsValid] = React.useState(true);
  const [isAuth, setIsAuth] = React.useState(false);
  const { error, isLoading, authorization } = useAuthentication();

  const onChangeEmail = (value: string) => {
    setEmail(value);
  };

  const onChangeName = (value: string) => {
    setName(value);
  };

  React.useEffect(() => {
    if (steps.storedValue) setEmail(steps.storedValue);
  }, [steps.storedValue]);

  React.useEffect(() => {
    const emailIsValid = email.match(emailRegex) !== null;
    setEmailIsValid(emailIsValid);

    if (emailIsValid) {
      dispatch(actions.form.addEmail(email));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [email]);

  React.useEffect(() => {
    setNameIsValid(true);
    dispatch(
      actions.user.update({
        username: name,
      })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [name]);

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

  const onNext = async () => {
    await authorize();
    steps.saveCurrent(email);
    steps.goNext();
  };

  return (
    <>
      <div className="palmistry-container__title-wrapper">
        <h2>{translate("/email.title")}</h2>
      </div>

      <Input
        className="palmistry-container__input"
        placeholder={translate("/email.placeholder_email")}
        type="text"
        value={email}
        onChange={onChangeEmail}
        floatingPlaceholder
      />

      <Input
        className="palmistry-container__input"
        placeholder={translate("/email.placeholder_name")}
        type="text"
        value={name}
        onChange={onChangeName}
        floatingPlaceholder
      />

      <div className="palmistry-container__description">
        <h3>{translate("/email.not_share")}</h3>
      </div>

      <div className="palmistry-container__policy">
        <p>
          {translate("privacy_policy", {
            eulaLink: (
              <a
                href="https://aura.wit.life/terms"
                target="_blank"
                rel="noopener noreferrer"
              >
                {translate("eula_link")}
              </a>
            ),
            privacyLink: (
              <a
                href="https://aura.wit.life/privacy"
                target="_blank"
                rel="noopener noreferrer"
              >
                {translate("privacy_notice")}
              </a>
            ),
            clickHere: (
              <a
                href="https://aura.wit.life/"
                target="_blank"
                rel="noopener noreferrer"
              >
                {translate("policy_here")}
              </a>
            ),
          })}
        </p>
      </div>

      <Button
        className="palmistry-container__button"
        type="button"
        active={emailIsValid && nameIsValid}
        disabled={!emailIsValid || !nameIsValid}
        onClick={onNext}
      >
        {isLoading && <Loader color={LoaderColor.White} />}

        {!isLoading &&
          !(!error?.length && !isLoading && isAuth) &&
          translate("continue")}

        {!error?.length && !isLoading && isAuth && (
          <img
            style={{ height: "30px", width: "auto" }}
            src="/SuccessIcon.webp"
            alt="Success Icon"
          />
        )}
      </Button>

      {isLoading && <Loader color={LoaderColor.White} />}

      {error?.length && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          {translate("went_wrong")}
        </Title>
      )}
    </>
  );
}
