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

const ResetPassword: React.FC<ResetPasswordProps> = ({ email, token }) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [changed, setChanged] = useState<boolean>(false);

  const { t } = useTranslation();
  const {
    formState: { errors },
    handleSubmit,
    register,
    getValues,
    setError,
  } = useForm<ResetPasswordForm>();

  const onSubmit = ({ password, repeatPassword }: ResetPasswordForm): void => {
    setLoading(true);
    setError('repeatPassword', null);

    axios
      .post<CustomResponse<string>>('/api/resetPassword', {
        password,
        passwordConfirmation: repeatPassword,
        token,
      })
      .then((response) => {
        const { ok, error: apiError } = response.data;
        if (!ok) {
          setError('repeatPassword', { message: apiError });
          setLoading(false);
        } else {
          setChanged(true);
        }
      });
  };

  return (
    <section className="wrapper">
      <article className="content">
        <h1>
          Recuperar
          <br />
          Contraseña
        </h1>
        <p className="instructionsTitle">
          Escribe la nueva contraseña y confírmala.
        </p>
        <p className="instructions">
          La contraseña deberá tener
          <br />8 carateres min. / Mayúsculas, minúsculas y números.
        </p>
        <span className="divider" />
        {changed ? (
          <>
            <h1>{t('PASSWORD_CHANGED')}</h1>
            <Link href="/login">
              <a href="/login" title={t('LOGIN')} className="textClick">
                <p>{t('LOGIN')}</p>
              </a>
            </Link>
          </>
        ) : (
          <>
            <form onSubmit={handleSubmit(onSubmit)} noValidate>
              <fieldset>
                <Field label="Email" htmlFor="email" vertical>
                  <input type="email" name="email" value={email} disabled />
                </Field>
                <Field
                  label="Contraseña"
                  htmlFor="password"
                  errorMessage={t(errors.password?.message)}
                  error={!!errors.password}
                  vertical
                >
                  <input
                    type="password"
                    name="password"
                    {...register('password', {
                      required: 'REQUIRED_PASSWORD',
                      pattern: {
                        message: 'INVALID_PASSWORD',
                        value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)\S{8,}$/,
                      },
                    })}
                  />
                </Field>
                <Field
                  label="Repetir Contraseña"
                  htmlFor="repeatPassword"
                  errorMessage={t(errors.repeatPassword?.message)}
                  error={!!errors.repeatPassword && !loading}
                  vertical
                >
                  <input
                    type="password"
                    name="repeatPassword"
                    {...register('repeatPassword', {
                      required: 'REQUIRED_REPEAT_PASSWORD',
                      validate: (value) =>
                        value !== getValues('password')
                          ? 'PASSWORDS_DONT_MATCH'
                          : undefined,
                    })}
                  />
                </Field>
                <RoundedButton
                  title="Confirmar"
                  type="submit"
                  size="big"
                  isLoading={loading}
                  rightIcon={<ArrowBigRight />}
                />
              </fieldset>
            </form>
            <Link href="/login">
              <a href="/login" title={t('CANCEL')} className="textClick">
                <p>{t('CANCEL')}</p>
              </a>
            </Link>
          </>
        )}
      </article>
    </section>
  );
};

export default ResetPassword;
