import React, { useState } from 'react';
import { login } from '../services/login';
import { useNavigate } from "react-router-dom";

const Login: React.FC = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);
    let navigate = useNavigate();

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        setLoading(true);
        try {
            await login(email, password);
            // redirect the user to the / page
            navigate('/');


        } catch (e: any) {
            setError(e.message);
        }
        setLoading(false);
    };

    return (
        <div className="bg-gray-200 h-screen flex items-center justify-center">
            <form onSubmit={handleSubmit} className="bg-white p-6 rounded-lg shadow-md">
                <h1 className="text-lg font-medium mb-4">Login</h1>
                <div className="mb-4">
                    <label className="block text-gray-700 font-medium mb-2">Email</label>
                    <input
                        className="border border-gray-400 p-2 rounded-lg w-full"
                        type="email"
                        value={email}
                        onChange={(event) => setEmail(event.target.value)}
                        required
                    />
                </div>
                <div className="mb-4">
                    <label className="block text-gray-700 font-medium mb-2">Password</label>
                    <input
                        className="border border-gray-400 p-2 rounded-lg w-full"
                        type="password"
                        value={password}
                        onChange={(event) => setPassword(event.target.value)}
                        required
                    />
                </div>
                <div>
                    {error && <p className="text-red-500">{error}</p>}
                </div>
                <button className="bg-indigo-500 text-white py-2 px-4 rounded-lg hover:bg-indigo-600" disabled={loading}>
                    {loading ? 'Loading...' : 'Login'}
                </button>
            </form>
        </div>
    );

};

export default Login;
