import React, { useState } from "react";
import Modal from "./Modal";
import "../../Style/LoginModal.css";
import Logo from '../../assets/images/logo.svg?react';
import TextField from '@mui/material/TextField';
import axios from 'axios';

const LoginModal = ({ onLogin, onClose }) => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [showPassword, setShowPassword] = React.useState(false);

  const handleClickShowPassword = () => setShowPassword((show) => !show);

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const { data } = await axios.post(
        `${import.meta.env.VITE_BACK_URL}/api/auth/login`,
        { login: username, password },
        {
          withCredentials: true,
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      if (data.success) {
        localStorage.setItem('access_token', data.access_token);
        onLogin(data.user);
        onClose();
      } else {
        setError(data.message || "Неверный логин или пароль");
      }
    } catch (err) {
      console.error('Ошибка при отправке запроса:', err);
      setError(err.response?.data?.message || "Ошибка при подключении к серверу");
    }
  };

  return (
    <Modal onClose={onClose}>
      <h2>Авторизация</h2>
      <form onSubmit={handleSubmit}>
        <TextField
          fullWidth
          id="user-login"
          label="Логин"
          variant="filled"
          margin="normal"
          required
          onChange={(e) => setUsername(e.target.value)}
          size="normal"
        />

        <TextField
          fullWidth
          id="user-password"
          label="Пароль"
          variant="filled"
          margin="normal"
          required
          type={showPassword ? 'text' : 'password'}
          onChange={(e) => setPassword(e.target.value)}
          size="normal"
        />

        {error && <p className="error">{error}</p>}
        <button type="submit">Войти</button>
      </form>
    </Modal>
  );
};

export default LoginModal;