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, Flex, Loader, Paper, Text, TextInput } from '@mantine/core';

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 (
    <Paper flex={1} maw='500' withBorder radius='md' p='xl'>
      <Flex direction='column' gap='sm'>
        <Text size="xl" fw={500}>
          Вход
        </Text>

        <form onSubmit={handleSubmit(onSubmit)}>
          <Flex direction='column' gap='sm'>
            <TextInput
              label='Логин'
              required
              {...register('username', { required: 'Введите логин' })}
              error={errors.username?.message}
            />

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

            <Flex justify='flex-end' gap='sm'>
              <Button component='a' href='/auth/password-reset' variant='transparent'>
                Восстановить пароль
              </Button>
            </Flex>

            <Flex gap='sm'>
              <Button disabled={!isValid} type="submit" flex={1} variant='filled'>
                {isSubmitting ? <Loader size={16} /> : 'Вход'}
              </Button>

              {/* <Button component='a' flex={1} href='/auth/signup' type="button" variant='light'>
                Регистрация
              </Button> */}
            </Flex>
          </Flex>
        </form>
      </Flex>
    </Paper>
  );
};

export default SignIn;