"use client";

import { Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useTransition } from "react";
import { deleteHireDraft } from "@/actions/hireDrafts";
import { useHireWizard } from "@/components/hire/HireWizardContext";
import { useToast } from "@/components/ui/Toast";
import { fmtDate } from "@/lib/format";

type Draft = { id: string; step: number; payload: Record<string, unknown>; updated_at: string };

export function DraftsCard({ drafts }: { drafts: Draft[] }) {
  const { openWizard } = useHireWizard();
  const { showToast } = useToast();
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  if (drafts.length === 0) return null;

  function handleDelete(id: string) {
    startTransition(async () => {
      const result = await deleteHireDraft(id);
      if (result.success) {
        showToast("Entwurf gelöscht.");
        router.refresh();
      } else {
        showToast(result.error ?? "Fehler beim Löschen.", "error");
      }
    });
  }

  return (
    <div className="rounded border border-border bg-white p-4">
      <h2 className="mb-3 text-sm font-bold text-ink">Entwürfe – Neueinstellungen</h2>
      <ul className="flex flex-col divide-y divide-border">
        {drafts.map((d) => {
          const firstName = typeof d.payload.firstName === "string" ? d.payload.firstName : "";
          const lastName = typeof d.payload.lastName === "string" ? d.payload.lastName : "";
          const name = [firstName, lastName].filter(Boolean).join(" ") || "Ohne Namen";
          return (
            <li key={d.id} className="flex items-center justify-between py-2 text-sm">
              <div>
                <span className="font-semibold text-ink">{name}</span>
                <span className="ml-2 text-xs text-ink-muted">Gespeichert am {fmtDate(d.updated_at)}</span>
              </div>
              <div className="flex items-center gap-3">
                <button type="button" onClick={() => openWizard(d.id)} className="text-xs font-semibold text-brand-700 hover:underline">
                  Fortsetzen
                </button>
                <button
                  type="button"
                  onClick={() => handleDelete(d.id)}
                  disabled={pending}
                  aria-label="Entwurf löschen"
                  className="text-ink-muted hover:text-danger-solid"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
