import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useTranslation } from 'react-i18next';
import { useForm, useWatch } from 'react-hook-form';
import { useRouter } from 'next/router';
import axios from 'axios';
import Field from '../../common/Field';
import ArrowBigRight from '../../icons/ArrowBigRight';
import RoundedButton from '../../common/RoundedButton';
import RoundedLink from '../../common/RoundedLink';
import { LoginForm } from '../../../model/components/login';
import { CustomResponse } from '../../../model/common';
import { User } from '../../../model/user';

const inscriptionOpen = true;

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 Login: React.FC = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    setError,
    control,
  } = useForm<LoginForm>();

  const email = useWatch<LoginForm>({ control, name: 'email' });
  const { t } = useTranslation();

  const [valid, setValid] = useState<boolean>(false);
  const [invalid, setInvalid] = useState<boolean>(false);

  const router = useRouter();

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

  const onSubmit = async (data: LoginForm): Promise<void> => {
    const response = await axios.post<CustomResponse<User>>('/api/login', data);
    if (!response.data?.ok) {
      setError('password', { message: t(response.data?.error) });
    } else {
      router.push('/');
    }
  };

  return (
    <section className="wrapper">
      <article className="content">
        <h1>Entrar</h1>
        <p className="instructions">
          Si ya estás registrado introduce tu email y contraseña, si no,
          selecciona nuevo usuario.
        </p>
        <span className="divider" />
        <form onSubmit={handleSubmit(onSubmit)} noValidate>
          <fieldset>
            <Field
              label="Email"
              htmlFor="email"
              errorMessage={t(errors.email?.message)}
              error={!!errors.email || invalid}
              vertical
              checked={valid}
            >
              <input
                type="email"
                name="email"
                {...register('email', {
                  required: 'REQUIRED_EMAIL',
                  pattern: { message: 'INVALID_EMAIL', value: /^\S+@\S+.\S$/i },
                })}
              />
            </Field>
            <Field
              label="Contraseña"
              htmlFor="password"
              errorMessage={t(errors.password?.message)}
              vertical
              error={!!errors.password}
            >
              <input
                type="password"
                name="password"
                {...register('password', { required: 'REQUIRED_PASSWORD' })}
              />
            </Field>
            <RoundedButton
              title="Entrar"
              type="submit"
              size="big"
              rightIcon={<ArrowBigRight />}
            />
          </fieldset>
        </form>
        <Link href="/forgotPassword">
          <a
            href="/forgotPassword"
            title="Olvidé mi contraseña"
            className="textClick"
          >
            <p>He olvidado mi contraseña</p>
          </a>
        </Link>
        <span className="divider" />
        {inscriptionOpen ? (
          <RoundedLink
            route="/signUp"
            title="Nuevo Usuario"
            rightIcon={<ArrowBigRight />}
            size="tiny"
            className="signUpClick white"
          />
        ) : (
          <p className="inscriptionClosed">Registro Cerrado</p>
        )}
      </article>
    </section>
  );
};

export default Login;
