"use client";

import { useRef, useState, useTransition } from "react";
import { Trash2 } from "lucide-react";
import { deleteDomainAction } from "@/app/(dashboard)/domains/actions";
import { Button } from "@/components/ui/button";

/** An app's domain is hidden (restorable); a domain added by hand is deleted. The dialog says which. */
export function DeleteDomainButton({ id, name, appCount }: { id: string; name: string; appCount: number }) {
  const dialogRef = useRef<HTMLDialogElement>(null);
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const hides = appCount > 0;

  function confirmDelete() {
    startTransition(async () => {
      setError(null);
      const result = await deleteDomainAction(id);
      if (result.ok) dialogRef.current?.close();
      else setError(result.error);
    });
  }

  return (
    <>
      <Button
        variant="ghost"
        size="sm"
        className="text-red-600 hover:bg-red-50 hover:text-red-700"
        onClick={() => dialogRef.current?.showModal()}
        aria-label={`Delete ${name}`}
      >
        <Trash2 className="size-3.5" aria-hidden />
        Delete
      </Button>

      <dialog
        ref={dialogRef}
        aria-labelledby={`delete-domain-title-${id}`}
        className="m-auto w-[calc(100%-2rem)] max-w-md rounded-lg border border-slate-200 bg-white p-0 text-left shadow-xl backdrop:bg-slate-950/40"
      >
        <div className="p-5">
          <h2 id={`delete-domain-title-${id}`} className="text-sm font-semibold text-slate-900">
            {hides ? "Hide domain?" : "Delete domain?"}
          </h2>
          <p className="mt-2 whitespace-normal text-sm text-slate-600">
            <span className="font-medium text-slate-900">{name}</span>{" "}
            {hides
              ? `is used by ${appCount} ${appCount === 1 ? "app" : "apps"}, so it will be hidden instead: no longer checked or listed, and not shown on the dashboard. You can restore it from "Hidden domains".`
              : "will no longer be checked and its details (registrar, dates) will be removed."}
          </p>
          {error && (
            <p role="alert" className="mt-3 text-sm text-red-600">
              {error}
            </p>
          )}
        </div>
        <div className="flex justify-end gap-2 border-t border-slate-200 bg-slate-50 px-5 py-3">
          <Button variant="secondary" onClick={() => dialogRef.current?.close()} disabled={pending}>
            Cancel
          </Button>
          <Button variant="danger" onClick={confirmDelete} disabled={pending}>
            {pending ? "Working…" : hides ? "Hide" : "Delete"}
          </Button>
        </div>
      </dialog>
    </>
  );
}
