import React, { useState } from 'react';
import { loginUser } from '../api';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../AuthContext';  // Подключаем AuthContext

const Login = () => {
    const [login, setLogin] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const navigate = useNavigate();
    const { login: authenticate } = useAuth();  // Вытаскиваем метод login из контекста

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

        try {
            const userData = await loginUser({ login, password });
            localStorage.setItem('token', userData.access_token);
            authenticate();
            navigate('/');
        } catch (error) {
            setError(error.detail ? error.detail : 'Ошибка авторизации');
        }
    };

    return (
        <div className="container mt-5">
            <h2 className="text-center">Вход</h2>
            {error && <p className="text-danger text-center">{error}</p>}
            <form onSubmit={handleSubmit} className="border p-4 rounded shadow">
                <div className="form-group">
                    <label htmlFor="login">Логин</label>
                    <input
                        type="text"
                        id="login"
                        className="form-control"
                        value={login}
                        onChange={(e) => setLogin(e.target.value)}
                        required
                    />
                </div>
                <div className="form-group">
                    <label htmlFor="password">Пароль</label>
                    <input
                        type="password"
                        id="password"
                        className="form-control"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />
                </div>
                <button type="submit" className="btn btn-primary btn-block">Войти</button>
            </form>
        </div>
    );
};

export default Login;
