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

function Login({ setIsLoggedIn }) {
    const [username, setUsernameInput] = useState('');
    const [password, setPassword] = useState('');
    const [message, setMessage] = useState('');
    const navigate = useNavigate();
    const { setUserId, setUsername } = useContext(UserContext);

    const handleLogin = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post('http://localhost:5000/login', { username, password });
            setMessage(res.data.message);
            if (res.data.success) {
                setIsLoggedIn(true);
                setUserId(res.data.userId);
                setUsername(username);
                navigate('/');
            } else {
                setMessage(res.data.message);
            }
        } catch (err) {
            setMessage(err.response ? err.response.data.error : 'Error logging in');
        }
    };

    return (
        <div className="form-container">
            <h2>Login</h2>
            <form onSubmit={handleLogin}>
                <input
                    type="text"
                    placeholder="Username"
                    value={username}
                    onChange={(e) => setUsernameInput(e.target.value)}
                    required
                />
                <input
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                />
                <button className="btn" type="submit">Login</button>
            </form>
            <p>{message}</p>
        </div>
    );
}

export default Login;