"use client";

import { useState } from "react";
import { Trash2, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";

interface DeleteButtonProps {
  id: string;
  onDelete: (id: string) => Promise<any>;
  className?: string;
}

export function DeleteButton({ id, onDelete, className }: DeleteButtonProps) {
  const [isDeleting, setIsDeleting] = useState(false);
  const [confirm, setConfirm] = useState(false);

  const handleDelete = async () => {
    if (!confirm) {
      setConfirm(true);
      setTimeout(() => setConfirm(false), 3000);
      return;
    }

    setIsDeleting(true);
    try {
      await onDelete(id);
    } catch (error) {
      console.error(error);
      alert("Failed to delete.");
      setIsDeleting(false);
    }
  };

  return (
    <button
      onClick={handleDelete}
      disabled={isDeleting}
      className={cn(
        "p-2 rounded-lg transition-all flex items-center gap-2",
        confirm 
          ? "bg-destructive text-destructive-foreground hover:bg-destructive/90" 
          : "text-foreground-muted hover:text-destructive hover:bg-destructive/10",
        className
      )}
      title={confirm ? "Click again to confirm" : "Delete"}
    >
      {isDeleting ? (
        <Loader2 size={16} className="animate-spin" />
      ) : (
        <Trash2 size={16} />
      )}
      {confirm && <span className="text-[10px] font-bold uppercase">Confirm?</span>}
    </button>
  );
}
