import { useEffect, useState } from "preact/hooks";

type Student = {
  numEtud: number;
  nom: string;
  prenom: string;
  idPromo: string;
};
type Promotion = { id: string; annee: string };

export default function ConsultStudents() {
  const [students, setStudents] = useState<Student[]>([]);
  const [promos, setPromos] = useState<Promotion[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filterPromo, setFilterPromo] = useState("");
  const [filterNom, setFilterNom] = useState("");

  async function load() {
    try {
      const [sRes, pRes] = await Promise.all([
        fetch("/students/api/students"),
        fetch("/students/api/promotions"),
      ]);
      if (!sRes.ok) throw new Error("Impossible de charger les élèves");
      setStudents(await sRes.json());
      if (pRes.ok) setPromos(await pRes.json());
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    load();
  }, []);

  async function deleteStudent(numEtud: number) {
    if (!confirm(`Supprimer l'élève #${numEtud} ?`)) return;
    try {
      const res = await fetch(`/students/api/students/${numEtud}`, {
        method: "DELETE",
      });
      if (!res.ok) throw new Error("Suppression échouée");
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur");
    }
  }

  const filtered = students.filter((s) => {
    const matchPromo = !filterPromo || s.idPromo === filterPromo;
    const matchNom = !filterNom ||
      `${s.nom} ${s.prenom}`.toLowerCase().includes(filterNom.toLowerCase());
    return matchPromo && matchNom;
  });

  return (
    <div class="page-content">
      <h2 class="page-title">Gestion des Élèves</h2>

      {error && <p class="state-error">{error}</p>}

      <div class="toolbar">
        <a
          class="btn btn-primary"
          href="/students/upload"
          f-partial="/students/partials/upload"
        >
          Importer xlsx
        </a>
      </div>

      <div class="filters">
        <select
          class="filter-select"
          value={filterPromo}
          onChange={(e) =>
            setFilterPromo((e.target as HTMLSelectElement).value)}
        >
          <option value="">Toutes les promos</option>
          {promos.map((p) => (
            <option key={p.id} value={p.id}>{p.id} — {p.annee}</option>
          ))}
        </select>
        <input
          class="filter-input"
          placeholder="Rechercher par nom…"
          value={filterNom}
          onInput={(e) => setFilterNom((e.target as HTMLInputElement).value)}
        />
      </div>

      {loading
        ? <p class="state-loading">Chargement…</p>
        : (
          <div class="data-table-wrap">
            <table class="data-table">
              <thead>
                <tr>
                  <th>N° étud.</th>
                  <th>Nom</th>
                  <th>Prénom</th>
                  <th>Promo</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.length === 0
                  ? (
                    <tr>
                      <td colspan={5} class="state-empty">
                        Aucun élève trouvé
                      </td>
                    </tr>
                  )
                  : filtered.map((s) => (
                    <tr key={s.numEtud}>
                      <td class="col-dim">{s.numEtud}</td>
                      <td>{s.nom}</td>
                      <td>{s.prenom}</td>
                      <td>{s.idPromo}</td>
                      <td>
                        <div class="col-actions">
                          <a
                            class="btn btn-sm btn-secondary"
                            href={`/students/edit/${s.numEtud}`}
                            f-client-nav={false}
                          >
                            ✏
                          </a>
                          <button
                            type="button"
                            class="btn btn-sm btn-danger"
                            onClick={() => deleteStudent(s.numEtud)}
                          >
                            🗑
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        )}
    </div>
  );
}
