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

type Promotion = { id: string; annee: string | null };

export default function AdminPromotions() {
  const [promos, setPromos] = useState<Promotion[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [newId, setNewId] = useState("");
  const [newAnnee, setNewAnnee] = useState("");
  const [creating, setCreating] = useState(false);

  async function load() {
    try {
      const res = await fetch("/students/api/promotions");
      if (!res.ok) throw new Error("Impossible de charger les promotions");
      setPromos(await res.json());
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur");
    } finally {
      setLoading(false);
    }
  }

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

  async function createPromo() {
    if (!newId.trim()) return;
    setCreating(true);
    try {
      const res = await fetch("/students/api/promotions", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          idPromo: newId.trim(),
          annee: newAnnee.trim() || null,
        }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error ?? "Création échouée");
      }
      setNewId("");
      setNewAnnee("");
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur");
    } finally {
      setCreating(false);
    }
  }

  async function deletePromo(id: string) {
    if (!confirm(`Supprimer la promotion ${id} ?`)) return;
    try {
      const res = await fetch(
        `/students/api/promotions/${encodeURIComponent(id)}`,
        {
          method: "DELETE",
        },
      );
      if (!res.ok) throw new Error("Suppression échouée");
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur");
    }
  }

  return (
    <div class="page-content">
      <h2 class="page-title">Gestion des Promotions</h2>

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

      <div class="form-row">
        <input
          class="form-input"
          placeholder="Identifiant (ex: 4A22)"
          value={newId}
          onInput={(e) => setNewId((e.target as HTMLInputElement).value)}
        />
        <input
          class="form-input"
          placeholder="Année (ex: 2022-2023)"
          value={newAnnee}
          onInput={(e) => setNewAnnee((e.target as HTMLInputElement).value)}
          style="min-width: 14rem"
        />
        <button
          type="button"
          class="btn btn-primary"
          onClick={createPromo}
          disabled={creating}
        >
          + Ajouter
        </button>
      </div>

      {loading
        ? <p class="state-loading">Chargement…</p>
        : (
          <div class="data-table-wrap">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Identifiant</th>
                  <th>Année</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                {promos.length === 0
                  ? (
                    <tr>
                      <td colspan={3} class="state-empty">
                        Aucune promotion enregistrée
                      </td>
                    </tr>
                  )
                  : promos.map((p) => (
                    <tr key={p.id}>
                      <td class="col-promo">{p.id}</td>
                      <td>{p.annee ?? "—"}</td>
                      <td>
                        <button
                          type="button"
                          class="btn btn-sm btn-danger"
                          onClick={() => deletePromo(p.id)}
                        >
                          🗑
                        </button>
                      </td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        )}
    </div>
  );
}
