// @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts"
import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs";
import { useRef } from "preact/hooks";
import { useSignal } from "@preact/signals";

export default function UploadStudents() {
  const file = useSignal<File | null>(null);
  const dragging = useSignal(false);
  const uploading = useSignal(false);
  const error = useSignal<string | null>(null);
  const success = useSignal<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  function pickFile(f: File) {
    if (!f.name.match(/\.xlsx?$/i)) {
      error.value = "Fichier invalide — format attendu : .xlsx";
      return;
    }
    file.value = f;
    error.value = null;
    success.value = null;
  }

  function onDragOver(e: DragEvent) {
    e.preventDefault();
    dragging.value = true;
  }

  function onDragLeave() {
    dragging.value = false;
  }

  function onDrop(e: DragEvent) {
    e.preventDefault();
    dragging.value = false;
    const f = e.dataTransfer?.files?.[0];
    if (f) pickFile(f);
  }

  function onInputChange(e: Event) {
    const f = (e.target as HTMLInputElement).files?.[0];
    if (f) pickFile(f);
  }

  async function doImport() {
    if (!file.value) return;
    uploading.value = true;
    error.value = null;
    success.value = null;

    try {
      const arrayBuffer = await file.value.arrayBuffer();
      const workbook = XLSX.read(arrayBuffer, { type: "array" });
      let imported = 0;
      let failed = 0;

      for (const sheetName of workbook.SheetNames) {
        const sheet = workbook.Sheets[sheetName];
        const rows = XLSX.utils.sheet_to_json<{
          numEtud: number;
          nom: string;
          prenom: string;
        }>(sheet, { header: ["numEtud", "nom", "prenom"], range: 1 });

        for (const row of rows) {
          const res = await fetch("/students/api/students", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ ...row, idPromo: sheetName }),
          });
          if (res.ok) imported++;
          else failed++;
        }
      }

      success.value =
        `Import terminé — ${imported} ajouté${imported !== 1 ? "s" : ""}${
          failed > 0 ? `, ${failed} erreur${failed !== 1 ? "s" : ""}` : ""
        }`;
    } catch {
      error.value = "Erreur lors de la lecture du fichier.";
    } finally {
      uploading.value = false;
    }
  }

  function downloadTemplate() {
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet([["numEtud", "nom", "prenom"]]);
    XLSX.utils.book_append_sheet(wb, ws, "4A22");
    XLSX.writeFile(wb, "modele_etudiants.xlsx");
  }

  return (
    <div>
      <input
        ref={inputRef}
        type="file"
        accept=".xlsx,.xls"
        style="display:none"
        onChange={onInputChange}
      />

      <div
        class={`drop-zone${dragging.value ? " dragging" : ""}`}
        onDragOver={onDragOver}
        onDragLeave={onDragLeave}
        onDrop={onDrop}
        onClick={() => inputRef.current?.click()}
      >
        <span class="drop-zone-icon">⬇</span>
        {file.value
          ? <span class="drop-zone-file">{file.value.name}</span>
          : (
            <>
              <span class="drop-zone-text">Glisser le fichier .xlsx ici</span>
              <span class="drop-zone-hint">ou cliquer pour parcourir</span>
            </>
          )}
      </div>

      {error.value && <p class="state-error">{error.value}</p>}
      {success.value && (
        <p style="font-size:0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.75rem">
          {success.value}
        </p>
      )}

      <div class="upload-actions">
        <button
          type="button"
          class="btn btn-primary"
          onClick={doImport}
          disabled={!file.value || uploading.value}
        >
          {uploading.value ? "…" : "⊕ Importer"}
        </button>
        <button
          type="button"
          class="btn btn-secondary"
          onClick={downloadTemplate}
        >
          ⊕ Télécharger Modèle
        </button>
      </div>

      <p class="upload-format">
        Format : <strong>promo</strong> (nom de la feuille) |{" "}
        <strong>numEtud</strong> | <strong>nom</strong> |{" "}
        <strong>prénom</strong>
      </p>
    </div>
  );
}
