"use client";

import { useState, type FormEvent } from "react";
import type { DiffResponse } from "@/lib/api/types";
import { Card, CardBody } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { IconAlertTriangle, IconUpload } from "@/components/icons";
import { ApplyFlow } from "./apply-flow";

type FetchState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "error"; message: string }
  | { status: "success"; data: DiffResponse };

export function ImportFlow() {
  const [state, setState] = useState<FetchState>({ status: "idle" });
  const [file, setFile] = useState<File | null>(null);
  const [sheetName, setSheetName] = useState("");
  const [machineType, setMachineType] = useState("");

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!file) return;
    setState({ status: "loading" });

    const form = new FormData();
    form.append("xlsx_file", file);
    if (sheetName.trim()) form.append("sheet_name", sheetName.trim());
    if (machineType.trim()) form.append("machine_type", machineType.trim());

    try {
      const res = await fetch("/api/report-templates/diff", {
        method: "POST",
        body: form,
      });
      const body = (await res.json().catch(() => null)) as
        | (DiffResponse & { message?: string })
        | { success: false; message?: string; error?: string }
        | null;

      if (!res.ok || !body || body.success === false) {
        const message =
          (body && "message" in body && body.message) ||
          (body && "error" in body && body.error) ||
          `Erreur HTTP ${res.status}`;
        setState({ status: "error", message: String(message) });
        return;
      }
      setState({ status: "success", data: body as DiffResponse });
    } catch {
      setState({ status: "error", message: "Erreur réseau" });
    }
  }

  const loading = state.status === "loading";

  return (
    <div className="space-y-6">
      <Card>
        <CardBody>
          <form onSubmit={handleSubmit}>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="sm:col-span-2">
                <label
                  htmlFor="xlsx_file"
                  className="mb-1.5 block text-xs font-medium text-foreground"
                >
                  Fichier XLSX (ou CSV)
                </label>
                <input
                  id="xlsx_file"
                  type="file"
                  accept=".xlsx,.csv"
                  required
                  onChange={(e) => setFile(e.target.files?.[0] ?? null)}
                  className="block w-full rounded-md border border-border-strong bg-surface px-3 py-2 text-sm text-foreground shadow-sm file:mr-3 file:cursor-pointer file:rounded file:border-0 file:bg-surface-2 file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-foreground hover:file:bg-surface-3"
                />
              </div>
              <div>
                <label
                  htmlFor="sheet_name"
                  className="mb-1.5 block text-xs font-medium text-foreground"
                >
                  Onglet (optionnel)
                </label>
                <input
                  id="sheet_name"
                  type="text"
                  value={sheetName}
                  onChange={(e) => setSheetName(e.target.value)}
                  placeholder="Tous les onglets si vide"
                  className="w-full rounded-md border border-border-strong bg-surface px-3 py-2 text-sm text-foreground shadow-sm placeholder:text-subtle-foreground focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent-ring/40"
                />
              </div>
              <div>
                <label
                  htmlFor="machine_type"
                  className="mb-1.5 block text-xs font-medium text-foreground"
                >
                  Forcer le type de machine (optionnel)
                </label>
                <input
                  id="machine_type"
                  type="text"
                  value={machineType}
                  onChange={(e) => setMachineType(e.target.value)}
                  placeholder="Si l'auto-détection rate"
                  className="w-full rounded-md border border-border-strong bg-surface px-3 py-2 text-sm text-foreground shadow-sm placeholder:text-subtle-foreground focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent-ring/40"
                />
              </div>
            </div>
            <div className="mt-4 flex items-center justify-between gap-3 flex-wrap">
              <p className="text-xs text-muted-foreground">
                Aucune écriture en base — l&apos;endpoint{" "}
                <code className="font-mono text-foreground">diff</code> est
                read-only.
              </p>
              <Button
                type="submit"
                disabled={!file}
                loading={loading}
                icon={!loading ? <IconUpload size={14} /> : undefined}
              >
                {loading ? "Calcul du diff…" : "Calculer le diff"}
              </Button>
            </div>
          </form>
        </CardBody>
      </Card>

      {state.status === "loading" && <DiffSkeleton />}

      {state.status === "error" && (
        <Card className="mf-fade-in">
          <CardBody>
            <div className="flex items-start gap-3">
              <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-danger-subtle text-danger ring-1 ring-red-200">
                <IconAlertTriangle size={16} />
              </div>
              <div className="min-w-0">
                <p className="text-sm font-medium text-foreground">
                  Le diff n&apos;a pas pu être calculé
                </p>
                <p className="mt-1 text-sm text-muted-foreground break-words">
                  {state.message}
                </p>
              </div>
            </div>
          </CardBody>
        </Card>
      )}

      {state.status === "success" && file && (
        <div className="space-y-6 mf-fade-in">
          <p className="text-sm text-muted-foreground">
            <span className="font-medium text-foreground">
              {state.data.data.templates.length}
            </span>{" "}
            template
            {state.data.data.templates.length > 1 ? "s" : ""} extrait
            {state.data.data.templates.length > 1 ? "s" : ""}.
          </p>
          {state.data.data.templates.map((tpl, i) => (
            <ApplyFlow
              key={`${tpl.sheet_name}-${i}`}
              template={tpl}
              file={file}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function DiffSkeleton() {
  return (
    <Card className="mf-fade-in">
      <CardBody className="space-y-4">
        <div className="flex items-center gap-3">
          <Skeleton className="h-5 w-48" />
          <Skeleton className="h-4 w-24" />
        </div>
        <div className="flex flex-wrap gap-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-5 w-20" />
          ))}
        </div>
        <div className="space-y-2 pt-2">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-10 w-full" />
          ))}
        </div>
      </CardBody>
    </Card>
  );
}
