import React from 'react';
import { useTranslation } from "react-i18next";
import { useDispatch } from "react-redux";

import { PatchPayload } from "@/api/resources/User";
import { Step } from '@/hooks/palmistry/use-steps';
import { useAuth } from "@/auth";
import { useApi, ApiError, extractErrorMessage } from "@/api";
import useSteps from '@/hooks/palmistry/use-steps';
import Button from '@/components/palmistry/button/button';
import Input from '@/components/palmistry/input/input';
import { getClientTimezone } from "@/locales";
import { actions } from "@/store";
import Title from "@/components/Title";
import ErrorText from "@/components/ErrorText";
import Loader, { LoaderColor } from "@/components/Loader";

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

export default function StepEmail() {
  const api = useApi();
  const { signUp } = useAuth();
  const { t, i18n } = useTranslation();
  const dispatch = useDispatch();

  const steps = useSteps();

  const [email, setEmail] = React.useState(steps.storedValue);
  const [emailIsValid, setEmailIsValid] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  const [isAuth, setIsAuth] = React.useState(false);
  const [apiError, setApiError] = React.useState<ApiError | null>(null);
  const [error, setError] = React.useState<boolean>(false);
  const timezone = getClientTimezone();
  const locale = i18n.language;

  const onChangeEmail = (value: string) => {
    setEmail(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));
    }
  }, [email]);

  const authorization = async () => {
    try {
      setIsLoading(true);
      const auth = await api.auth({ email, timezone, locale });
      const { auth: { token, user } } = auth;

      signUp(token, user);
      const payload: PatchPayload = {
        user: {
          profile_attributes: {
            birthday: steps.getStoredValue(Step.Birthdate),
            gender: steps.getStoredValue(Step.Gender),
          },
        },
        token,
      };

      const relationshipStatus = steps.getStoredValue(Step.RelationshipStatus);
      if (relationshipStatus) {
        payload.user.profile_attributes!.relationship_status = relationshipStatus;
      }

      const updatedUser = await api.updateUser(payload).catch((error) => console.log("Error: ", error));

      if (updatedUser?.user) dispatch(actions.user.update(updatedUser.user));

      dispatch(actions.status.update("registred"));

      setIsLoading(false);
      setIsAuth(true);
    } catch (error) {
      console.error(error);
      if (error instanceof ApiError) {
        setApiError(error as ApiError);
      } else {
        setError(true);
      }
      setIsLoading(false);
    }
  };

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

  return (
    <>
      <div className="palmistry-container__title-wrapper">
        <h2>Enter your email to get your advanced Palmistry reading with AURA</h2>
      </div>

      <Input
        className="palmistry-container__input"
        placeholder="You Email"
        type="text"
        value={email}
        onChange={onChangeEmail}
        floatingPlaceholder
      />

      <div className="palmistry-container__description">
        <h3>We don’t share any personal information.</h3>
      </div>

      <div className="palmistry-container__policy">
        <p>
          By clicking "Continue" below you agree to AURA{' '}
          <a href="https://aura.wit.life/terms" target="_blank" rel="noreferrer nofollow">
            EULA
          </a>{' '}
          and{' '}
          <a href="https://aura.wit.life/privacy" target="_blank" rel="noreferrer nofollow">
            Privacy Policy
          </a>
          .
        </p>
      </div>

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

        {!isLoading && !(!apiError && !error && !isLoading && isAuth) && t("_continue")}

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

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

      {(error || apiError) && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          Something went wrong
        </Title>
      )}

      {apiError && (
        <ErrorText
          size="medium"
          isShown={Boolean(apiError)}
          message={apiError ? extractErrorMessage(apiError) : null}
        />
      )}
    </>
  );
}
