import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import Header from './Header';

const Login = () => {
    const navigate = useNavigate();
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);
    
    const handleRegisterClick = () => {
        navigate('/registration'); // Переход к регистрации
    };
    
    const handleLogin = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);
        try {
            const newUser = { username, password };
            await axios.post('/api/users/login', newUser,
                { 
                    withCredentials: true 
                    /*headers: { 
                        'Content-Type': 'application/json' 
                    }*/
                }
            );
            setTimeout(() => {
                navigate('/profile');
            }, 500);
        } catch (err) {
            setError(err.response.data.detail || 'Ошибка входа');
        } finally {
            setLoading(false);
        }
    };

  	return (
    <>
        <Header />
        <div className="login-page">
          <h2>Вход в систему</h2>
          {
            error && <div className="error">{error}</div>
          }
          <form onSubmit={handleLogin}>
            <div>
              <label>Логин:</label>
              <input
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                required
              />
            </div>
            <div>
              <label>Пароль:</label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
              />
            </div>
            <button type="submit" disabled={loading}>
              {loading ? 'Вход...' : 'Войти'}
            </button>
          </form>
          <button onClick={handleRegisterClick}>
            Зарегистрироваться
          </button>
        </div>
	  </>
  );
};

export default Login;