import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';

export default function Login() {
  const { login } = useAuth();
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState(null);
  const [busy, setBusy] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(null); setBusy(true);
    try {
      await login(email, password);
      navigate('/');
    } catch (e) {
      setErr(e.message);
    } finally { setBusy(false); }
  };

  return (
    <div className="login-shell">
      <form className="card login-card" onSubmit={submit}>
        <h2 style={{ marginTop: 0 }}>Connexion</h2>
        {err && <div className="error">{err}</div>}
        <label>Email</label>
        <input type="email" required value={email} onChange={e => setEmail(e.target.value)} />
        <div style={{ height: 10 }} />
        <label>Mot de passe</label>
        <input type="password" required value={password} onChange={e => setPassword(e.target.value)} />
        <div style={{ height: 16 }} />
        <button className="primary" type="submit" disabled={busy} style={{ width: '100%' }}>
          {busy ? '…' : 'Se connecter'}
        </button>
        <p className="text-muted" style={{ marginTop: 16, textAlign: 'center' }}>
          Pas encore de compte ? <Link to="/register">Créer un compte</Link>
        </p>
      </form>
    </div>
  );
}
