
import React, { useState } from 'react';
import { Loader2, Trash2, AlertTriangle } from 'lucide-react';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { usePaymentPlans } from '@/hooks/usePaymentPlans';
import { toESTDateDisplay } from '@/lib/timezoneUtils';

export function PaymentPlanItemDeleteDialog({ open, onOpenChange, item, onSuccess }) {
  const { deletePaymentPlanItem } = usePaymentPlans();
  const [isDeleting, setIsDeleting] = useState(false);

  const handleDelete = async () => {
    if (!item) return;
    setIsDeleting(true);
    try {
      const success = await deletePaymentPlanItem(item.id);
      if (success) { onSuccess?.(); onOpenChange(false); }
    } finally { setIsDeleting(false); }
  };

  if (!item) return null;

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle className="flex items-center text-destructive gap-2">
            <AlertTriangle className="h-5 w-5" /> Delete Payment Item?
          </AlertDialogTitle>
          <AlertDialogDescription className="space-y-3 pt-2">
            <p>Are you sure you want to delete this payment item? This action cannot be undone.</p>
            <div className="bg-muted p-3 rounded-md border text-sm space-y-1">
              <div className="flex justify-between"><span className="text-muted-foreground">Description:</span><span className="font-medium">{item.description}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">Due Date:</span><span className="font-medium">{toESTDateDisplay(item.due_date)}</span></div>
              <div className="flex justify-between"><span className="text-muted-foreground">Amount:</span><span className="font-medium">${parseFloat(item.amount).toFixed(2)}</span></div>
            </div>
            {item.received_date && (
              <p className="text-amber-600 font-medium text-xs mt-2">Warning: This item is marked as PAID. Deleting it will affect financial records.</p>
            )}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
          <Button variant="destructive" onClick={handleDelete} disabled={isDeleting}>
            {isDeleting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
            Delete Item
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
