import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useForm, useWatch } from 'react-hook-form';
import axios from 'axios';
import { useTranslation } from 'react-i18next';
import Field from '../../common/Field';
import ArrowBigRight from '../../icons/ArrowBigRight';
import RoundedButton from '../../common/RoundedButton';
import { ForgotPasswordForm } from '../../../model/components/forgotPassword';
import { CustomResponse } from '../../../model/common';

const regExp = new RegExp(
  /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,
  'i',
);

const ForgotPassword: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [changed, setChanged] = useState<boolean>(false);
  const { t } = useTranslation();

  const {
    formState: { errors },
    setError,
    handleSubmit,
    register,
    control,
  } = useForm<ForgotPasswordForm>();

  const emailField = useWatch<ForgotPasswordForm>({ control, name: 'email' });
  const [valid, setValid] = useState<boolean>(false);
  const [invalid, setInvalid] = useState<boolean>(false);

  useEffect(() => {
    if (emailField && emailField.length) {
      if (!regExp.test(emailField)) {
        setInvalid(true);
        setValid(false);
      } else {
        setValid(true);
        setInvalid(false);
      }
    } else {
      setValid(false);
      setInvalid(false);
    }
  }, [emailField]);

  const onSubmit = ({ email }: ForgotPasswordForm): void => {
    setLoading(true);
    setError('email', null);

    axios
      .post<CustomResponse<string>>('/api/forgotPassword', {
        email,
      })
      .then((data) => {
        const { ok, error: apiError } = data.data;
        if (!ok) {
          setError('email', { message: apiError });
        } else {
          setChanged(true);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.error(err.stack || err.message || err);
        setLoading(false);
      });
  };

  return (
    <section className="wrapper">
      <article className="content">
        <h1>
          Recuperar
          <br />
          Contraseña
        </h1>
        <p className="instructionsTitle">Escribe tu email.</p>
        <p className="instructions">
          Te mandaremos un correo al email para que cambies tu contraseña por
          una nueva.
        </p>
        <span className="divider" />
        {changed ? (
          <h1>{t('EMAIL_SENT')}</h1>
        ) : (
          <form onSubmit={handleSubmit(onSubmit)} noValidate>
            <fieldset>
              <Field
                label="Email"
                htmlFor="email"
                errorMessage={t(errors.email?.message)}
                error={!loading && (!!errors.email || invalid)}
                vertical
                checked={valid && !errors.email}
              >
                <input
                  type="email"
                  name="email"
                  {...register('email', {
                    required: 'REQUIRED_EMAIL',
                    pattern: {
                      message: 'INVALID_EMAIL',
                      value: /^\S+@\S+.\S$/i,
                    },
                  })}
                />
              </Field>
              <RoundedButton
                title="Enviar"
                type="submit"
                size="big"
                isLoading={loading}
                rightIcon={<ArrowBigRight />}
              />
            </fieldset>
          </form>
        )}
        <Link href="/login">
          <a
            href="/login"
            title={changed ? t('LOGIN') : t('CANCEL')}
            className="textClick"
          >
            <p>{changed ? t('LOGIN') : t('CANCEL')}</p>
          </a>
        </Link>
      </article>
    </section>
  );
};

export default ForgotPassword;
