import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { Avatar } from '@/components/avatar';
import { Logo } from '@/components/logo';
import { Button } from '@/components/ui/button';
import { useDemoAccounts, useDemoLogin, useLogin } from '@/auth/use-auth';

/** Écran 1 de la maquette validée : connexion sobre + mode démonstration
 *  (ADR-002) visible uniquement quand l'API expose /auth/demo-accounts. */
export default function PageConnexion() {
  const navigate = useNavigate();
  const login = useLogin();
  const demoLogin = useDemoLogin();
  const { data: demoAccounts, isError: apiInjoignable } = useDemoAccounts();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const surConnexion = (e: FormEvent) => {
    e.preventDefault();
    login.mutate(
      { email, password },
      { onSuccess: () => navigate('/', { replace: true }) },
    );
  };

  const surDemo = (userId: string) => {
    demoLogin.mutate(userId, {
      onSuccess: () => navigate('/', { replace: true }),
    });
  };

  return (
    <div className="conn">
      <div className="carte-conn">
        <Logo sousTitre="Maintenance d'ascenseurs" />
        {apiInjoignable ? (
          <p className="erreur-form" role="alert">
            L'API ne répond pas — en local, démarrez-la avec <code>pnpm dev</code>{' '}
            (à la racine, elle lance l'API et le web ensemble).
          </p>
        ) : null}
        <form
          onSubmit={surConnexion}
          className="flex flex-col gap-[14px]"
          aria-label="Connexion"
        >
          <div className="champ">
            <label htmlFor="email">Email</label>
            <input
              id="email"
              type="email"
              autoComplete="email"
              placeholder="prenom.nom@spelev.ma"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
          </div>
          <div className="champ">
            <label htmlFor="mdp">Mot de passe</label>
            <input
              id="mdp"
              type="password"
              autoComplete="current-password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          {login.isError ? (
            <p className="erreur-form" role="alert">
              Email ou mot de passe incorrect. Vérifiez votre saisie.
            </p>
          ) : null}
          <Button
            type="submit"
            variant="prim"
            className="justify-center"
            disabled={login.isPending}
          >
            Se connecter
          </Button>
        </form>

        {demoAccounts && demoAccounts.length > 0 ? (
          <>
            <div className="sep">Mode démonstration</div>
            <div className="demo-liste">
              {demoAccounts.map((compte) => (
                <button
                  key={compte.id}
                  type="button"
                  onClick={() => surDemo(compte.id)}
                  disabled={demoLogin.isPending}
                >
                  <Avatar initials={compte.initials} roleName={compte.roleName} />
                  {compte.displayName}
                  <span className="role">{compte.roleName}</span>
                </button>
              ))}
            </div>
            <div className="text-center">
              <span className="chip-demo">DEMO_MODE=true — absent en production</span>
            </div>
          </>
        ) : null}
      </div>
    </div>
  );
}
