import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate, Link } from 'react-router-dom';

const Login = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const navigate = useNavigate();

    const handleLogin = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post('http://localhost:5000/api/auth/login', { username, password });
            localStorage.setItem('token', res.data.token);
            navigate('/dashboard');
        } catch (err) {
            setError(err.response?.data?.error || 'Authentication Failed');
        }
    };

    return (
        <div className="min-h-screen bg-slate-100 flex items-center justify-center">
            <form onSubmit={handleLogin} className="bg-white p-8 rounded-lg shadow-md w-96">
                <h2 className="text-2xl font-bold text-slate-800 mb-6 text-center">SmartPark Rubavu Auth</h2>
                {error && <p className="bg-red-100 text-red-700 p-2 rounded mb-4 text-sm">{error}</p>}
                <div className="mb-4">
                    <label className="block text-slate-600 text-sm mb-2">Username</label>
                    <input type="text" className="w-full border p-2 rounded focus:outline-emerald-500" value={username} onChange={e=>setUsername(e.target.value)} required/>
                </div>
                <div className="mb-6">
                    <label className="block text-slate-600 text-sm mb-2">Password</label>
                    <input type="password" className="w-full border p-2 rounded focus:outline-emerald-500" value={password} onChange={e=>setPassword(e.target.value)} required/>
                </div>
                <button type="submit" className="w-full bg-emerald-600 text-white p-2 rounded hover:bg-emerald-700 transition">Login</button>
            <p className="text-sm text-slate-600 text-center mt-4">
    Don't have an account yet?{' '}
    <Link to="/register" className="text-emerald-600 font-semibold hover:underline">
        Register here
    </Link>
</p>
            </form>
            
        </div>
    );
};

export default Login;