import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Api as auth } from '../client/auth_client.ts';
import '../LoadingScreen.css';
import './Login.css'

const LoginForm: React.FC = () => {
    const [login, setLogin] = useState('');
    const [password, setPassword] = useState('');
    const [problem, setProblem] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const navigate = useNavigate();
    const client = new auth({ baseUrl: 'auth' });

    useEffect(() => {
        document.title = 'Login - My App';
    }, []);

    const handleEnterKey = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            handleLogin();
        }
    };

    const handleLogin = async () => {
        setIsLoading(true);
        try {
            const response = await client.login.loginCreate({ login: login, pass: password });

            if (response.status === 200 && response.data && response.data.token) {
                const token = response.data.token;
                localStorage.setItem('authToken', token);
                navigate('/');
            }
        } catch (error) {
            setProblem('Login failed. Please check your credentials.');
        } finally {
            setIsLoading(false);
        }
    };

    if (isLoading) {
        return (
            <div className="loading-screen">
                <div className="spinner">
                    <div className="lds-ring"><div></div><div></div><div></div><div></div></div>
                </div>
            </div>
        );
    }

    return (
        <div className="d-flex justify-content-center align-items-center vh-100">
            <div className="">
                <div className="card p-4 shadow-lg login-container">
                    <h3 className="text-center mb-4">Login</h3>
                    <div className="text-danger">{problem}</div>
                    <div className="mb-3">
                        <label htmlFor="username" className="form-label">Username</label>
                        <input
                            id="username"
                            type="text"
                            onKeyDown={handleEnterKey}
                            value={login}
                            onChange={(e) => setLogin(e.target.value)}
                            className="form-control"
                            required
                        />
                    </div>
                    <div className="mb-3">
                        <label htmlFor="password" className="form-label">Password</label>
                        <input
                            id="password"
                            type="password"
                            onKeyDown={handleEnterKey}
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            className="form-control"
                            required
                        />
                    </div>
                    <button className="btn btn-primary btn-lg btn-block w-100" onClick={handleLogin}>Login</button>
                </div>
            </div>
        </div>
    );
};

export default LoginForm;
