// components/delete-vendor-dialog.tsx
"use client";

import * as React from "react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { AlertTriangle, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { deleteRfqVendor } from "../service";

interface DeleteVendorDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  rfqId: number;
  vendorData: {
    detailId: number;
    vendorId: number;
    vendorName: string;
    vendorCode?: string | null;
    hasQuotation: boolean;  // quotationStatus가 있는지 여부
  };
  onSuccess?: () => void;
}

export function DeleteVendorDialog({
  open,
  onOpenChange,
  rfqId,
  vendorData,
  onSuccess,
}: DeleteVendorDialogProps) {
  const [isDeleting, setIsDeleting] = React.useState(false);

  const handleDelete = async () => {
    // quotationStatus가 있으면 삭제 불가 (추가 보호)
    if (vendorData.hasQuotation) {
      toast.error("견적서가 제출된 벤더는 삭제할 수 없습니다.");
      return;
    }

    try {
      setIsDeleting(true);
      
      const result = await deleteRfqVendor({
        rfqId,
        detailId: vendorData.detailId,
        vendorId: vendorData.vendorId,
      });

      if (result.success) {
        toast.success(result.message || "벤더가 삭제되었습니다.");
        onSuccess?.();
        onOpenChange(false);
      } else {
        toast.error(result.message || "삭제에 실패했습니다.");
      }
    } catch (error) {
      console.error("벤더 삭제 실패:", error);
      toast.error("삭제 중 오류가 발생했습니다.");
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle className="flex items-center gap-2">
            <AlertTriangle className="h-5 w-5 text-destructive" />
            벤더 삭제 확인
          </AlertDialogTitle>
          <AlertDialogDescription asChild>
            <div className="space-y-2">
              <p>
                <strong>{vendorData.vendorName}</strong>
                {vendorData.vendorCode && ` (${vendorData.vendorCode})`}을(를) 
                RFQ 목록에서 삭제하시겠습니까?
              </p>
              
              {vendorData.hasQuotation && (
                <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
                  <p className="font-semibold">⚠️ 주의: 견적서가 제출된 벤더입니다.</p>
                  <p>견적서가 제출된 벤더는 삭제할 수 없습니다.</p>
                </div>
              )}
              
              {!vendorData.hasQuotation && (
                <p className="text-sm text-muted-foreground">
                  이 작업은 되돌릴 수 없습니다. 삭제 후에는 해당 벤더의 모든 RFQ 관련 정보가 제거됩니다.
                </p>
              )}
            </div>
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isDeleting}>취소</AlertDialogCancel>
          <AlertDialogAction
            onClick={handleDelete}
            disabled={isDeleting || vendorData.hasQuotation}
            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            {isDeleting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                삭제 중...
              </>
            ) : (
              "삭제"
            )}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}