"use client";

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

export function DeleteProjectButton({ id, code, name }: { id: string; code: string; name: string }) {
  const dialogRef = useRef<HTMLDialogElement>(null);
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function confirmDelete() {
    startTransition(async () => {
      setError(null);
      const result = await deleteProjectAction(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()}
      >
        <Trash2 className="size-3.5" aria-hidden />
        Delete
      </Button>

      <dialog
        ref={dialogRef}
        aria-labelledby={`delete-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-title-${id}`} className="text-sm font-semibold text-slate-900">
            Delete application?
          </h2>
          <p className="mt-2 whitespace-normal text-sm text-slate-600">
            <span className="font-medium text-slate-900">
              {code} — {name}
            </span>{" "}
            will be removed from the dashboard and will no longer be monitored. Its health-check history is kept.
          </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 ? "Deleting…" : "Delete"}
          </Button>
        </div>
      </dialog>
    </>
  );
}
