"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";

type ActionResult = { ok: true } | { error: string };

export function ConfirmDeleteButton({
  onDelete,
  label,
}: {
  onDelete: () => Promise<ActionResult>;
  label: string;
}) {
  const router = useRouter();
  const [confirming, setConfirming] = useState(false);
  const [error, setError] = useState("");
  const [isPending, startTransition] = useTransition();

  if (confirming) {
    return (
      <span className="inline-flex items-center gap-2 flex-wrap">
        <span className="text-xs text-neutral-600 whitespace-nowrap">Delete {label}?</span>
        <button
          onClick={() =>
            startTransition(async () => {
              const result = await onDelete();
              if ("error" in result) {
                setError(result.error);
                setConfirming(false);
              } else {
                router.refresh();
              }
            })
          }
          disabled={isPending}
          className="text-xs font-medium text-danger-600 hover:text-danger-800 hover:underline disabled:opacity-50 whitespace-nowrap"
        >
          {isPending ? "Deleting…" : "Confirm"}
        </button>
        <button
          onClick={() => { setConfirming(false); setError(""); }}
          className="text-xs text-neutral-500 hover:underline whitespace-nowrap"
        >
          Cancel
        </button>
        {error && <span className="text-xs text-danger-600 block w-full">{error}</span>}
      </span>
    );
  }

  return (
    <button
      onClick={() => setConfirming(true)}
      className="text-xs text-danger-500 hover:text-danger-700 hover:underline"
    >
      Delete
    </button>
  );
}
