import { useForm, SubmitHandler } from 'react-hook-form';
import { AxiosError, AxiosResponse } from 'axios';
import { ApiResponse, LoginFormData } from '../../interfaces/auth';
import { login, setUserData } from '../../store/auth';
import { useNavigate } from 'react-router-dom';
import AuthService from '../../services/AuthService';
import UserService from '../../services/UserService';
import { Button, Field, Input, Link, Spinner, Text } from '@fluentui/react-components';
import { pages } from '../../constants/app';

const SignIn = () => {
  const { register, handleSubmit, setError, formState: { errors, isSubmitting, isValid } } = useForm<LoginFormData>({
    defaultValues: {
      username: '',
      password: '',
      grant_type: 'password',
      scope: '',
      client_id: '',
      client_secret: ''
    }
  })

  const navigate = useNavigate();

  const onSubmit: SubmitHandler<LoginFormData> = async (data) => {
    const formBody = new URLSearchParams();
    for (const key in data) {
      formBody.append(key, data[key as keyof LoginFormData] as string);
    }

    try {
      const response: AxiosResponse<ApiResponse> = await AuthService.login(formBody)

      const token = response.data.access_token

      const userDataResponse: AxiosResponse<ApiResponse> = await UserService.getCurrentUser(token)

      setUserData(JSON.stringify(userDataResponse.data))

      login(token)

      navigate('/');
    } catch (error: unknown) {
      if ((error as AxiosError).response?.data) {
        const err = (error as AxiosError).response?.data
        setError('password', {
          message: (err as { detail: string })?.detail
        })
      }
    }
  };

  return (
    <div style={{
      display: 'flex',
      margin: 'auto',
      flexDirection: 'column',
      gap: '1rem',
      maxWidth: '400px',
      width: '100%',
      height: 'min-content',
      borderRadius: '1rem',
      border: '1px solid #00000030',
      padding: '2rem',
      background: 'var(--colorNeutralBackground1)'
    }}>
      <Text align='center' size={500} weight='bold'>
        Вход
      </Text>

      <form onSubmit={handleSubmit(onSubmit)}>
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          gap: '1rem'
        }}>

          <Field label={'Логин'} validationState={errors.username?.message ? 'error' : 'none'}>
            <Input
              required
              {...register('username', { required: 'Введите логин' })}
            />
          </Field>

          <Field label={'Пароль'} validationState={errors.password?.message ? 'error' : 'none'}>
            <Input
              required
              type='password'
              {...register('password', { required: 'Введите пароль' })}
            />
          </Field>

          <Link href='/auth/password-reset'>
            Восстановить пароль
          </Link>

          <Button disabled={!isValid} type="submit" appearance='primary' icon={isSubmitting ? <Spinner size='extra-tiny' /> : undefined}>
            Вход
          </Button>

          {pages.find(page => page.path === '/auth/signup')?.enabled &&
            <Button as='a' href='/auth/signup' type="button" appearance='subtle'>
              Регистрация
            </Button>
          }
        </div>
      </form>
    </div>
  );
};

export default SignIn;