import { useForm, SubmitHandler } from 'react-hook-form';
import { TextField, Button, Container, Typography, Box, Stack, Link, CircularProgress } from '@mui/material';
import { 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';

const SignIn = () => {
  const { register, handleSubmit, formState: { errors, isSubmitting } } = 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) {
      console.error('Ошибка при входе:', error);
    }
  };

  return (
    <Container maxWidth="sm">
      <Box my={4}>
        <Typography variant="h4" component="h1" gutterBottom>
          Вход
        </Typography>

        <form onSubmit={handleSubmit(onSubmit)}>
          <Stack spacing={2}>
            <TextField
              fullWidth
              margin="normal"
              label="Логин"
              required
              {...register('username', { required: 'Введите логин' })}
              error={!!errors.username}
              helperText={errors.username?.message}
            />

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

            <Box sx={{ display: 'flex', gap: '16px', justifyContent: 'flex-end' }}>
              <Link href="/auth/password-reset" color="primary">
                Восстановить пароль
              </Link>
            </Box>

            <Box sx={{ display: 'flex', gap: '16px' }}>
              <Button fullWidth type="submit" variant="contained" color="primary">
                {isSubmitting ? <CircularProgress size={16} /> : 'Вход'}
              </Button>

              <Button fullWidth href="/auth/signup" type="button" variant="text" color="primary">
                Регистрация
              </Button>
            </Box>
          </Stack>


        </form>
      </Box>
    </Container>
  );
};

export default SignIn;