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

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

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

    try {
      const response = await axios.post('http://localhost:5000/api/login', {
        username,
        password
      });
      localStorage.setItem('hospital_token', response.data.token);
      localStorage.setItem('hospital_user', JSON.stringify(response.data.user));
      navigate('/dashboard');
    } catch (err) {
      setError(err.response?.data?.message || 'Invalid credentials or connection error.');
    }
  };

  return (
    <div className="min-h-screen bg-slate-50 flex items-center justify-center p-4">
      <div className="max-w-md w-full bg-white border border-slate-200 rounded-2xl shadow-xl p-8 space-y-6">
        <div className="text-center">
          <h1 className="text-2xl font-extrabold text-teal-600 tracking-wide">🏥 HOSPITAL SYSTEM</h1>
          <p className="text-sm text-slate-500 mt-1">Sign in to manage clinical entries.</p>
        </div>

        {error && <div className="bg-red-50 text-red-600 border border-red-100 p-3 rounded-xl text-xs font-medium">⚠️ {error}</div>}

        <form onSubmit={handleLogin} className="space-y-5">
          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">Username</label>
            <input type="text" placeholder="Enter username" value={username} onChange={(e) => setUsername(e.target.value)} className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-800 focus:outline-none focus:border-teal-500" required />
          </div>

          <div className="space-y-1">
            <label className="text-xs font-bold text-slate-600 uppercase">Password</label>
            <input type="password" placeholder="••••••••" value={password} onChange={(e) => setPassword(e.target.value)} className="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-800 focus:outline-none focus:border-teal-500" required />
          </div>

          <button type="submit" className="w-full bg-teal-600 hover:bg-teal-700 text-white font-bold py-2.5 rounded-xl text-sm transition duration-200 cursor-pointer shadow-md shadow-teal-600/10">
            Sign In Securely
          </button>
        </form>

        <div className="text-center text-xs text-slate-500">
          New hospital staff? <Link to="/register" className="text-teal-600 font-bold hover:underline">Create account</Link>
        </div>
      </div>
    </div>
  );
}

export default Login;
