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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setMessage('');
    setLoading(true);

    try {
      const response = await axios.post('http://localhost:5001/api/auth/login', { username, password });
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('user', JSON.stringify(response.data.user));
      setMessage('Login successful');
      navigate('/dashboard');
    } catch (err) {
      setError(err.response?.data?.message || 'Login failed');
      console.error('Server Error:', err.response?.data || err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <div className="lms-card w-full max-w-md p-8 shadow-lg">
        <p className="text-xs font-semibold uppercase tracking-wider text-slate-400">Library LMS</p>
        <h1 className="mt-1 mb-6 text-2xl font-semibold text-white">Staff sign in</h1>

        {message && <p className="lms-alert-success">{message}</p>}
        {error && <p className="lms-alert-error">{error}</p>}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="lms-label">Username</label>
            <input
              type="text"
              required
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="lms-input"
            />
          </div>

          <div>
            <label className="lms-label">Password</label>
            <input
              type="password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="lms-input"
            />
          </div>

          <button type="submit" disabled={loading} className="lms-btn-primary w-full">
            {loading ? 'Signing in...' : 'Sign in'}
          </button>
        </form>

        <p className="mt-4 text-center text-xs text-slate-500">
          Default: admin / admin123 or librarian / lib123
        </p>
        <p className="mt-2 text-center text-xs">
          Don't have an account? <Link to="/register" className="text-blue-400 underline">Create one</Link>
        </p>
      </div>
    </div>
  );
}

export default Login;
