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

const Login = () => {
  const [Email, setEmail] = useState('');
  const [Password, setPassword] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');

    try {
      // Kohereza amakuru kuri server
      const res = await axios.post('http://localhost:5000/api/login', { 
        Email: Email, 
        Password: Password 
      });

      // Kubika token
      localStorage.setItem('token', res.data.token);
      navigate('/'); // Kwimukira kuri Dashboard
    } catch (err) {
      setError("Invalid Email or Password. Please try again.");
    }
  };

  return (
    <div className="flex justify-center items-center h-screen bg-gray-100">
      <form onSubmit={handleLogin} className="bg-white p-8 rounded-lg shadow-xl w-96">
        <h2 className="text-2xl font-bold mb-6 text-center text-blue-900">Admin Login</h2>
        
        {error && <p className="text-red-500 text-center mb-4 text-sm">{error}</p>}
        
        <input 
          type="email" placeholder="Email" required 
          className="w-full p-3 mb-4 border rounded focus:outline-none focus:ring-2 focus:ring-blue-600"
          onChange={(e) => setEmail(e.target.value)}
        />
        <input 
          type="password" placeholder="Password" required 
          className="w-full p-3 mb-6 border rounded focus:outline-none focus:ring-2 focus:ring-blue-600"
          onChange={(e) => setPassword(e.target.value)}
        />
        <button type="submit" className="w-full bg-blue-600 text-white p-3 rounded font-bold hover:bg-blue-700 transition">
          Login
        </button>
      </form>
    </div>
  );
};

export default Login;