import { useForm, SubmitHandler } from 'react-hook-form';
import { TextField, Button, Container, Typography, Box } 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 } } = 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)}>
          <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}
          />
          <Button type="submit" variant="contained" color="primary">
            Вход
          </Button>
          <Button href="/auth/signup" type="button" variant="text" color="primary">
            Регистрация
          </Button>
        </form>
      </Box>
    </Container>
  );
};

export default SignIn;