"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useConfirm, useToast } from "@/components/ui/DialogProvider";

export function ListDeleteButton({ id }: { id: string }) {
  const [deleting, setDeleting] = useState(false);
  const router = useRouter();
  const showConfirm = useConfirm();
  const showToast = useToast();

  const handleDelete = async () => {
    const ok = await showConfirm({
      title: "Eliminar cotización",
      message: "¿Eliminar esta cotización?",
      confirmText: "Eliminar",
      danger: true,
    });
    if (!ok) return;
    setDeleting(true);
    try {
      const res = await fetch(`/api/cotizaciones/${id}`, { method: "DELETE" });
      if (res.ok) router.refresh();
      else showToast("Error al eliminar", "error");
    } catch {
      showToast("Error al eliminar", "error");
    } finally {
      setDeleting(false);
    }
  };

  return (
    <button
      onClick={handleDelete}
      disabled={deleting}
      className="text-xs text-red-500 hover:text-red-700 disabled:opacity-50"
    >
      {deleting ? "..." : "Eliminar"}
    </button>
  );
}
