'use client';
import { ChangeEvent, FormEvent, useState } from 'react';
import Cookies from 'js-cookie';
import Link from 'next/link';
import Image from 'next/image';
import { useMutation } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/UI/Button';
import { Input } from '@/components/UI/Input';
import Icon from '@/components/Icon';
import { AuthorizationService, ILoginForm } from '@/services/AuthorizationService';
import { COOKIE_NAME } from '@/api/api';

export const Login = () => {
  const router = useRouter();
  const [isPasswordVisible, setIsPasswordVisible] = useState<boolean>(false);
  const [form, setForm] = useState<ILoginForm>({} as ILoginForm);
  const [error, setError] = useState<string>('');

  const { mutateAsync, isPending } = useMutation({
    mutationKey: ['login'],
    mutationFn: () => AuthorizationService.login(form),
    onSuccess: (data) => {
      if (data.result === 1) {
        setError('Введён неверный email или пароль');
        return;
      }
      if (data.JSESSIONID) {
        Cookies.set(COOKIE_NAME, data.JSESSIONID);
        router.push('/');
      }
    },
  });

  const handleChange = (e: ChangeEvent<HTMLInputElement>): void => {
    setForm((prev) => {
      return {
        ...prev,
        [e.target.name]: e.target.value,
      };
    });
    setError('');
  };

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    mutateAsync();
  };

  return (
    <section className='h-screen flex justify-center items-center overflow-hidden bg-[#041722] relative'>
      <div className='py-12 px-[72px] rounded-xl bg-white z-10'>
        <h1 className='text-2xl text-[26px] text-center font-bold text-[#011844]'>
          Вход в аккаунт
        </h1>
        <form className='mb-6 mt-8' onSubmit={handleSubmit}>
          <Input
            name='account'
            value={form?.account}
            onChange={handleChange}
            label='Email'
            placeholder='Enter your email'
            className='mb-6'
            autoFocus
            error={!!error}
          />
          <div className='flex justify-between items-center mb-3'>
            <p className='text-base leading-5 text-[#011844]'>Password</p>
            <Link href='/reset-password' className='text-base leading-5 text-[#011844]'>
              Забыли пароль?
            </Link>
          </div>
          <Input
            name='password'
            value={form?.password}
            onChange={handleChange}
            placeholder='Enter your password'
            type={isPasswordVisible ? 'text' : 'password'}
            icon={
              <button
                type='button'
                className='px-4 h-full'
                onClick={() => setIsPasswordVisible((prev) => !prev)}
              >
                <Icon src='/images/icons/icon-eye.svg' className='w-6 h-6' />
              </button>
            }
            error={!!error}
          />
          {error && <p className='mt-2 text-red-500 text-sm'>{error}</p>}

          <Button
            type='submit'
            className='shadow-[0px_4px_6px_-1px_#1F5D81] font-medium mt-8'
            disabled={!form?.account?.length || !form?.password?.length || isPending}
            isLoading={isPending}
          >
            Логин
          </Button>
        </form>

        <p className='flex items-center gap-2 text-base leading-4'>
          <span className='text-[#BEBEBF]'>У Вас нет аккаунта?</span>
          <Link href='/registration' className='text-black'>
            Зарегистрироваться
          </Link>
        </p>
      </div>
      <Image
        src='/images/authorization-ellipse-1.png'
        alt='ellipse'
        width={539}
        height={539}
        className='absolute bottom-0 left-0'
      />
      <Image
        src='/images/authorization-ellipse-2.png'
        alt='ellipse'
        width={539}
        height={539}
        className='absolute top-[-150px] right-0'
      />
    </section>
  );
};
