import React, { useState, ChangeEvent, FormEvent } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { TextField, Button, Container, Typography, Box } from '@mui/material';
import axios, { AxiosResponse } from 'axios';
import { SignInFormData, ApiResponse } from '../../types/auth';
import { UserData, useAuthStore } from '../../store/auth';
import { useNavigate } from 'react-router-dom';
import axiosInstance from '../../http/axiosInstance';
import AuthService from '../../services/AuthService';

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

  const authStore = useAuthStore();
  const navigate = useNavigate();

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

    try {
      const response: AxiosResponse<ApiResponse> = await axiosInstance.post(`/auth/login`, formBody, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      });
      console.log('Вход произошел успешно:', response.data);

      const token = response.data.access_token

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

      console.log('Пользователь:', userDataResponse.data)

      authStore.setUserData(JSON.stringify(userDataResponse.data))
      authStore.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="Логин"
            {...register('username', { required: 'Логин обязателен' })}
            error={!!errors.username}
            helperText={errors.username?.message}
          />
          <TextField
            fullWidth
            margin="normal"
            type="password"
            label="Пароль"
            {...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;