"use client";

import * as React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Trophy,
  TrendingUp,
  TrendingDown,
  AlertCircle,
  CheckCircle,
  XCircle,
  ChevronDown,
  ChevronUp,
  Info,
  DollarSign,
  Calendar,
  Package,
  Globe,
  FileText,
  Truck,
  AlertTriangle,
  Award,
  UserCheck,
  X,
  RefreshCw,
  Clock,
  Download,
  Paperclip,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { format } from "date-fns";
import { ko } from "date-fns/locale";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { ComparisonData, selectVendor, cancelVendorSelection, VendorResponseVersion } from "./compare-action";
import { createPO, createGeneralContract, createBidding } from "./contract-actions";
import { toast } from "sonner";
import { useRouter } from "next/navigation"

interface QuotationCompareViewProps {
  data: ComparisonData;
}

export function QuotationCompareView({ data }: QuotationCompareViewProps) {
  const [expandedItems, setExpandedItems] = React.useState<Set<number>>(new Set());
  const [selectedVendorId, setSelectedVendorId] = React.useState<string>("");
  const [showSelectionDialog, setShowSelectionDialog] = React.useState(false);
  const [showCancelDialog, setShowCancelDialog] = React.useState(false);
  const [showContractDialog, setShowContractDialog] = React.useState(false);
  const [showItemDetailsDialog, setShowItemDetailsDialog] = React.useState(false);
  const [selectedResponse, setSelectedResponse] = React.useState<VendorResponseVersion | null>(null);
  const [selectedVendorName, setSelectedVendorName] = React.useState<string>("");
  const [selectedContractType, setSelectedContractType] = React.useState<"PO" | "CONTRACT" | "BIDDING" | "">("");
  const [selectionReason, setSelectionReason] = React.useState("");
  const [cancelReason, setCancelReason] = React.useState("");
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const router = useRouter()

  const [selectedGeneralContractType, setSelectedGeneralContractType] = React.useState("");
  const [contractStartDate, setContractStartDate] = React.useState("");
  const [contractEndDate, setContractEndDate] = React.useState("");

  // 계약종류 옵션
  const contractTypes = [
    { value: 'UP', label: 'UP - 자재단가계약' },
    { value: 'LE', label: 'LE - 임대차계약' },
    { value: 'IL', label: 'IL - 개별운송계약' },
    { value: 'AL', label: 'AL - 연간운송계약' },
    { value: 'OS', label: 'OS - 외주용역계약' },
    { value: 'OW', label: 'OW - 도급계약' },
    { value: 'IS', label: 'IS - 검사계약' },
    { value: 'LO', label: 'LO - LOI (의향서)' },
    { value: 'FA', label: 'FA - Frame Agreement' },
    { value: 'SC', label: 'SC - 납품합의계약' },
    { value: 'OF', label: 'OF - 클레임상계계약' },
    { value: 'AW', label: 'AW - 사전작업합의' },
    { value: 'AD', label: 'AD - 사전납품합의' },
    { value: 'AM', label: 'AM - 설계계약' },
    { value: 'SC_SELL', label: 'SC - 폐기물매각계약' },
  ];

  // 입찰 관련 state 추가
  const [biddingContractType, setBiddingContractType] = React.useState<"unit_price" | "general" | "sale">("unit_price");
  const [biddingType, setBiddingType] = React.useState<string>("");
  const [awardCount, setAwardCount] = React.useState<"single" | "multiple">("single");
  const [biddingStartDate, setBiddingStartDate] = React.useState("");
  const [biddingEndDate, setBiddingEndDate] = React.useState("");

  // 입찰 옵션들
  const biddingContractTypes = [
    { value: 'unit_price', label: '단가계약' },
    { value: 'general', label: '일반계약' },
    { value: 'sale', label: '매각계약' }
  ];

  const biddingTypes = [
    { value: 'equipment', label: '기자재' },
    { value: 'construction', label: '공사' },
    { value: 'service', label: '용역' },
    { value: 'lease', label: '임차' },
    { value: 'steel_stock', label: '형강스톡' },
    { value: 'piping', label: '배관' },
    { value: 'transport', label: '운송' },
    { value: 'waste', label: '폐기물' },
    { value: 'sale', label: '매각' }
  ];

  const awardCounts = [
    { value: 'single', label: '단수' },
    { value: 'multiple', label: '복수' }
  ];

  // 선정된 업체 정보 확인
  const selectedVendor = data.vendors.find(v => v.isSelected);
  const hasSelection = !!selectedVendor;
  const isSelectionApproved = selectedVendor?.selectionApprovalStatus === "승인";
  const isPendingApproval = selectedVendor?.selectionApprovalStatus === "대기";
  const hasContract = selectedVendor?.contractStatus ? true : false;

  // 계약 진행 처리
  const handleContractCreation = async () => {
    if (!selectedContractType) {
      toast.error("계약 유형을 선택해주세요.");
      return;
    }

    // 일반계약인 경우 계약종류와 날짜 확인
    if (selectedContractType === "CONTRACT") {
      if (!selectedGeneralContractType) {
        toast.error("계약종류를 선택해주세요.");
        return;
      }
      if (!contractStartDate) {
        toast.error("계약 시작일을 선택해주세요.");
        return;
      }
      if (!contractEndDate) {
        toast.error("계약 종료일을 선택해주세요.");
        return;
      }
      if (new Date(contractStartDate) >= new Date(contractEndDate)) {
        toast.error("계약 종료일은 시작일보다 이후여야 합니다.");
        return;
      }
    }

    // 입찰 검증
    if (selectedContractType === "BIDDING") {
      if (!biddingContractType) {
        toast.error("계약구분을 선택해주세요.");
        return;
      }
      if (!biddingType) {
        toast.error("입찰유형을 선택해주세요.");
        return;
      }
      if (!biddingStartDate || !biddingEndDate) {
        toast.error("입찰 기간을 입력해주세요.");
        return;
      }
      if (new Date(biddingStartDate) >= new Date(biddingEndDate)) {
        toast.error("입찰 마감일은 시작일보다 이후여야 합니다.");
        return;
      }
    }

    if (!selectedVendor) {
      toast.error("선정된 업체가 없습니다.");
      return;
    }

    setIsSubmitting(true);

    try {
      let result;

      switch (selectedContractType) {
        case "PO":
          const poSelectionReason: string | undefined = selectedVendor.selectionReason || undefined;
          result = await createPO({
            rfqId: data.rfqInfo.id,
            vendorId: selectedVendor.vendorId,
            vendorName: selectedVendor.vendorName,
            totalAmount: selectedVendor.totalAmount,
            currency: selectedVendor.currency,
            selectionReason: poSelectionReason,

          });
          break;

        case "CONTRACT":
          result = await createGeneralContract({
            rfqId: data.rfqInfo.id,
            vendorId: selectedVendor.vendorId,
            vendorName: selectedVendor.vendorName,
            totalAmount: selectedVendor.totalAmount,
            currency: selectedVendor.currency,
            contractStartDate: new Date(contractStartDate),
            contractEndDate: new Date(contractEndDate),
            contractType: selectedGeneralContractType, // 계약종류 추가

          });
          break;

        case "BIDDING":
          result = await createBidding({
            rfqId: data.rfqInfo.id,
            vendorId: selectedVendor.vendorId,
            vendorName: selectedVendor.vendorName,
            totalAmount: selectedVendor.totalAmount,
            currency: selectedVendor.currency,
            contractType: biddingContractType,
            biddingType: biddingType,
            awardCount: awardCount,
            biddingStartDate: new Date(biddingStartDate),
            biddingEndDate: new Date(biddingEndDate),
          });
          break;

        default:
          throw new Error("올바른 계약 유형이 아닙니다.");
      }

      if (result.success) {
        toast.success(result.message || "계약 프로세스가 시작되었습니다.");
        setShowContractDialog(false);
        // 모든 state 초기화
        setSelectedContractType("");
        setSelectedGeneralContractType("");
        setContractStartDate("");
        setContractEndDate("");
        setBiddingContractType("unit_price");
        setBiddingType("");
        setAwardCount("single");
        setBiddingStartDate("");
        setBiddingEndDate("");
        router.refresh();
      } else {
        throw new Error(result.error || "계약 진행 중 오류가 발생했습니다.");
      }
    } catch (error) {
      console.error("계약 생성 오류:", error);
      toast.error(error instanceof Error ? error.message : "계약 진행 중 오류가 발생했습니다.");
    } finally {
      setIsSubmitting(false);
    }
  };

  // 컴포넌트 마운트 시 선정된 업체가 있으면 자동 선택
  React.useEffect(() => {
    if (selectedVendor) {
      setSelectedVendorId(selectedVendor.vendorId.toString());
    }
  }, [selectedVendor]);

  // 아이템 확장/축소 토글
  const toggleItemExpansion = (itemId: number) => {
    setExpandedItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(itemId)) {
        newSet.delete(itemId);
      } else {
        newSet.add(itemId);
      }
      return newSet;
    });
  };

  // 순위에 따른 색상
  const getRankColor = (rank: number) => {
    switch (rank) {
      case 1:
        return "text-green-600 bg-green-50";
      case 2:
        return "text-blue-600 bg-blue-50";
      case 3:
        return "text-orange-600 bg-orange-50";
      default:
        return "text-gray-600 bg-gray-50";
    }
  };

  // 가격 차이 색상
  const getVarianceColor = (variance: number) => {
    if (variance < -5) return "text-green-600";
    if (variance > 5) return "text-red-600";
    return "text-gray-600";
  };

  // 금액 포맷
  const formatAmount = (amount: number, currency: string = "KRW") => {
    return new Intl.NumberFormat("ko-KR", {
      style: "currency",
      currency: currency,
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
    }).format(amount);
  };

  // 업체 선정 처리
  const handleVendorSelection = async () => {
    if (!selectedVendorId) {
      toast.error("선정할 업체를 선택해주세요.");
      return;
    }

    if (!selectionReason.trim()) {
      toast.error("선정 사유를 입력해주세요.");
      return;
    }

    setIsSubmitting(true);
    try {
      const vendor = data.vendors.find(v => v.vendorId === parseInt(selectedVendorId));
      if (!vendor) {
        throw new Error("선택한 업체를 찾을 수 없습니다.");
      }

      // 최신 응답 정보 사용
      const latestResponse = vendor.responses[0];
      if (!latestResponse) {
        throw new Error("업체의 견적 정보를 찾을 수 없습니다.");
      }

      const result = await selectVendor({
        rfqId: data.rfqInfo.id,
        vendorId: vendor.vendorId,
        vendorName: vendor.vendorName,
        vendorCode: vendor.vendorCode,
        totalAmount: latestResponse.totalAmount,
        currency: latestResponse.currency,
        selectionReason: selectionReason,
        priceRank: latestResponse.rank || 0,
        hasConditionDifferences: latestResponse.conditionDifferences.hasDifferences,
        criticalDifferences: latestResponse.conditionDifferences.criticalDifferences,
      });

      if (result.success) {
        toast.success("업체가 성공적으로 선정되었습니다.");
        setShowSelectionDialog(false);
        setSelectionReason("");
        router.refresh()
      } else {
        throw new Error(result.error || "업체 선정 중 오류가 발생했습니다.");
      }
    } catch (error) {
      console.error("업체 선정 오류:", error);
      toast.error(error instanceof Error ? error.message : "업체 선정 중 오류가 발생했습니다.");
    } finally {
      setIsSubmitting(false);
    }
  };

  // 업체 선정 취소 처리
  const handleCancelSelection = async () => {
    if (!cancelReason.trim()) {
      toast.error("취소 사유를 입력해주세요.");
      return;
    }

    setIsSubmitting(true);
    try {
      // 파라미터를 올바르게 전달
      const result = await cancelVendorSelection(Number(data.rfqInfo.id), cancelReason);

      if (result.success) {
        toast.success("업체 선정이 취소되었습니다.");
        setShowCancelDialog(false);
        setCancelReason("");
        router.refresh()
      } else {
        throw new Error(result.error || "선정 취소 중 오류가 발생했습니다.");
      }
    } catch (error) {
      console.error("선정 취소 오류:", error);
      toast.error(error instanceof Error ? error.message : "선정 취소 중 오류가 발생했습니다.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* 상단 액션 바 */}
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold">견적 비교 분석</h2>
        <div className="flex gap-2">
          {hasSelection ? (
            <>
              {!isSelectionApproved && (
                <Button
                  variant="destructive"
                  onClick={() => setShowCancelDialog(true)}
                  className="gap-2"
                >
                  <X className="h-4 w-4" />
                  선정 취소
                </Button>
              )}
              <Button
                variant="outline"
                onClick={() => {
                  setSelectedVendorId("");
                  setShowSelectionDialog(true);
                }}
                disabled={isSelectionApproved}
                className="gap-2"
              >
                <RefreshCw className="h-4 w-4" />
                재선정
              </Button>
            </>
          ) : (
            <Button
              onClick={() => setShowSelectionDialog(true)}
              disabled={!selectedVendorId}
              className="gap-2"
            >
              <Award className="h-4 w-4" />
              업체 선정
            </Button>
          )}
        </div>
      </div>

      {/* 선정 상태 알림 */}
      {hasSelection && (
        <Alert className={cn(
          "border-2",
          hasContract
            ? "border-purple-500 bg-purple-50"
            : isSelectionApproved
              ? "border-green-500 bg-green-50"
              : isPendingApproval
                ? "border-yellow-500 bg-yellow-50"
                : "border-blue-500 bg-blue-50"
        )}>
          <div className="flex items-start justify-between">
            <div className="flex gap-3">
              {hasContract ? (
                <FileText className="h-5 w-5 text-purple-600 mt-0.5" />
              ) : isSelectionApproved ? (
                <CheckCircle className="h-5 w-5 text-green-600 mt-0.5" />
              ) : isPendingApproval ? (
                <Clock className="h-5 w-5 text-yellow-600 mt-0.5" />
              ) : (
                <Award className="h-5 w-5 text-blue-600 mt-0.5" />
              )}
              <div className="space-y-2">
                <AlertTitle className="text-lg">
                  {hasContract
                    ? "계약 진행중"
                    : isSelectionApproved
                      ? "업체 선정 승인 완료"
                      : isPendingApproval
                        ? "업체 선정 승인 대기중"
                        : "업체 선정 완료"}
                </AlertTitle>
                <AlertDescription className="space-y-1">
                  <p className="font-semibold">선정 업체: {selectedVendor.vendorName} ({selectedVendor.vendorCode})</p>
                  <p>선정 금액: {formatAmount(selectedVendor.totalAmount, selectedVendor.currency)}</p>
                  <p>선정일: {selectedVendor.selectionDate ? format(new Date(selectedVendor.selectionDate), "yyyy년 MM월 dd일", { locale: ko }) : "-"}</p>
                  <p>선정 사유: {selectedVendor.selectionReason || "-"}</p>
                  {selectedVendor.contractNo && (
                    <>
                      <div className="border-t pt-1 mt-2">
                        <p className="font-semibold">계약 정보</p>
                        <p>계약 번호: {selectedVendor.contractNo}</p>
                        <p>계약 상태: {selectedVendor.contractStatus}</p>
                        {selectedVendor.contractCreatedAt && (
                          <p>계약 생성일: {format(new Date(selectedVendor.contractCreatedAt), "yyyy년 MM월 dd일", { locale: ko })}</p>
                        )}
                      </div>
                    </>
                  )}
                  {selectedVendor.selectedByName && (
                    <p className="text-sm text-muted-foreground">선정자: {selectedVendor.selectedByName}</p>
                  )}
                </AlertDescription>
              </div>
            </div>
            {/* 계약 진행 버튼들을 알림 카드 안에도 추가 (선택사항) */}
            {!hasContract && !isPendingApproval && (
              <div className="flex flex-col gap-2">
                <Button
                  size="sm"
                  variant="default"
                  onClick={() => {
                    setSelectedContractType("PO");
                    setShowContractDialog(true);
                  }}
                  className="gap-1 bg-green-600 hover:bg-green-700 text-xs"
                >
                  <FileText className="h-3 w-3" />
                  PO 생성
                </Button>
                <Button
                  size="sm"
                  variant="default"
                  onClick={() => {
                    setSelectedContractType("CONTRACT");
                    setShowContractDialog(true);
                  }}
                  className="gap-1 bg-blue-600 hover:bg-blue-700 text-xs"
                >
                  <FileText className="h-3 w-3" />
                  일반계약
                </Button>
                {/* <Button
                  size="sm"
                  variant="default"
                  onClick={() => {
                    setSelectedContractType("BIDDING");
                    setShowContractDialog(true);
                  }}
                  className="gap-1 bg-purple-600 hover:bg-purple-700 text-xs"
                >
                  <Globe className="h-3 w-3" />
                  입찰
                </Button> */}
              </div>
            )}
          </div>
        </Alert>
      )}

      {/* 요약 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* 최저가 벤더 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium flex items-center gap-2">
              <Trophy className="h-4 w-4 text-yellow-500" />
              최저가 벤더
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-lg font-bold">{data.summary.lowestBidder}</p>
            <p className="text-sm text-muted-foreground">
              {formatAmount(data.summary.priceRange.min, data.summary.currency)}
            </p>
          </CardContent>
        </Card>

        {/* 선정 업체 또는 평균 가격 */}
        {hasSelection ? (
          <Card className="border-2 border-blue-200 bg-blue-50">
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium flex items-center gap-2">
                <UserCheck className="h-4 w-4 text-blue-600" />
                선정 업체
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-lg font-bold">{selectedVendor.vendorName}</p>
              <p className="text-sm text-blue-600">
                {formatAmount(selectedVendor.totalAmount, selectedVendor.currency)}
              </p>
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-medium flex items-center gap-2">
                <DollarSign className="h-4 w-4" />
                평균 가격
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-lg font-bold">
                {formatAmount(data.summary.priceRange.average, data.summary.currency)}
              </p>
              <p className="text-sm text-muted-foreground">
                {data.vendors.length}개 업체 평균
              </p>
            </CardContent>
          </Card>
        )}
      </div>

      {/* 탭 뷰 */}
      <Tabs defaultValue="overview" className="w-full">
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="overview">종합 비교</TabsTrigger>
          <TabsTrigger value="conditions">조건 비교</TabsTrigger>
        </TabsList>

        {/* 종합 비교 */}
        <TabsContent value="overview" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>협력업체별 차수별 견적</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b bg-gray-50">
                      {!hasSelection && <th className="text-left p-3 font-semibold">선택</th>}
                      <th className="text-left p-3 font-semibold">협력사 코드</th>
                      <th className="text-left p-3 font-semibold">협력사 명</th>
                      {(() => {
                        // 모든 차수 추출 (중복 제거 및 내림차순 정렬)
                        const allVersions = Array.from(
                          new Set(
                            data.vendors.flatMap(v => v.responses.map(r => r.responseVersion))
                          )
                        ).sort((a, b) => b - a);
                        
                        return allVersions.map(version => (
                          <th key={version} className="text-right p-3 font-semibold">
                            {version}차
                          </th>
                        ));
                      })()}
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {data.vendors.map((vendor) => (
                      <tr
                        key={vendor.vendorId}
                        className={cn(
                          "hover:bg-gray-50 transition-colors",
                          vendor.isSelected && "bg-blue-50"
                        )}
                      >
                        {!hasSelection && (
                          <td className="p-3">
                            <input
                              type="radio"
                              name="vendor-selection"
                              value={vendor.vendorId}
                              checked={selectedVendorId === vendor.vendorId.toString()}
                              onChange={(e) => setSelectedVendorId(e.target.value)}
                              className="h-4 w-4 text-blue-600"
                            />
                          </td>
                        )}
                        <td className="p-3 text-sm font-medium">{vendor.vendorCode}</td>
                        <td className="p-3">
                          <div className="flex items-center gap-2">
                            <span className="font-semibold">{vendor.vendorName}</span>
                            {vendor.isSelected && (
                              <Badge className="bg-blue-600 text-xs">선정</Badge>
                            )}
                          </div>
                        </td>
                        {(() => {
                          const allVersions = Array.from(
                            new Set(
                              data.vendors.flatMap(v => v.responses.map(r => r.responseVersion))
                            )
                          ).sort((a, b) => b - a);
                          
                          return allVersions.map(version => {
                            const response = vendor.responses.find(r => r.responseVersion === version);
                            
                            return (
                              <td key={version} className="p-3 text-right">
                                {response ? (
                                  <Button
                                    variant="link"
                                    size="sm"
                                    className="h-auto p-0 font-bold text-blue-600 hover:text-blue-800"
                                    onClick={() => {
                                      setSelectedResponse(response);
                                      setSelectedVendorName(vendor.vendorName);
                                      setShowItemDetailsDialog(true);
                                    }}
                                  >
                                    {formatAmount(response.totalAmount, response.currency)}
                                  </Button>
                                ) : (
                                  <span className="text-sm text-gray-400">-</span>
                                )}
                              </td>
                            );
                          });
                        })()}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 조건 비교 */}
        <TabsContent value="conditions" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>거래 조건 비교</CardTitle>
            </CardHeader>
            <CardContent className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-3 font-semibold" rowSpan={2}>항목</th>
                  </tr>
                  <tr className="border-b bg-gray-50">
                    {data.vendors.map((vendor) => (
                      <React.Fragment key={vendor.vendorId}>
                        <th className={cn(
                          "text-center p-2 text-xs font-medium border-r",
                          vendor.isSelected && "bg-blue-50"
                        )}>
                          SHI 제시
                        </th>
                        <th className={cn(
                          "text-center p-2 text-xs font-medium",
                          vendor.isSelected && "bg-blue-50"
                        )}>
                          <div className="font-bold">
                            {vendor.vendorName}
                            </div>
                        {vendor.isSelected && (
                          <Badge className="ml-2 bg-blue-600 text-xs">선정</Badge>
                        )}
                        </th>
                      </React.Fragment>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y">
                  {/* 통화 */}
                  <tr>
                    <td className="p-3 font-medium">통화</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0]; // 최신 응답 (이미 정렬되어 있음)
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            {vendor.buyerConditions.currency}
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              {latestResponse?.vendorConditions?.currency || vendor.buyerConditions.currency}
                              {latestResponse?.vendorConditions?.currency && latestResponse.vendorConditions.currency !== vendor.buyerConditions.currency && (
                                <Badge variant="destructive" className="text-xs">변경</Badge>
                              )}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>

                  {/* 지급조건 */}
                  <tr>
                    <td className="p-3 font-medium">지급조건</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0];
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <TooltipProvider>
                              <Tooltip>
                                <TooltipTrigger className="cursor-help border-b border-dashed">
                                  {vendor.buyerConditions.paymentTermsCode}
                                </TooltipTrigger>
                                <TooltipContent>
                                  {vendor.buyerConditions.paymentTermsDesc}
                                </TooltipContent>
                              </Tooltip>
                            </TooltipProvider>
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              <TooltipProvider>
                                <Tooltip>
                                  <TooltipTrigger className="cursor-help border-b border-dashed">
                                    {latestResponse?.vendorConditions?.paymentTermsCode || vendor.buyerConditions.paymentTermsCode}
                                  </TooltipTrigger>
                                  <TooltipContent>
                                    {latestResponse?.vendorConditions?.paymentTermsDesc || vendor.buyerConditions.paymentTermsDesc}
                                  </TooltipContent>
                                </Tooltip>
                              </TooltipProvider>
                              {latestResponse?.vendorConditions?.paymentTermsCode &&
                                latestResponse.vendorConditions.paymentTermsCode !== vendor.buyerConditions.paymentTermsCode && (
                                  <Badge variant="outline" className="text-xs">변경</Badge>
                                )}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>

                  {/* 인코텀즈 */}
                  <tr>
                    <td className="p-3 font-medium">인코텀즈</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0];
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <TooltipProvider>
                              <Tooltip>
                                <TooltipTrigger className="cursor-help border-b border-dashed">
                                  {vendor.buyerConditions.incotermsCode}
                                </TooltipTrigger>
                                <TooltipContent>
                                  {vendor.buyerConditions.incotermsDesc}
                                </TooltipContent>
                              </Tooltip>
                            </TooltipProvider>
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              <TooltipProvider>
                                <Tooltip>
                                  <TooltipTrigger className="cursor-help border-b border-dashed">
                                    {latestResponse?.vendorConditions?.incotermsCode || vendor.buyerConditions.incotermsCode}
                                  </TooltipTrigger>
                                  <TooltipContent>
                                    {latestResponse?.vendorConditions?.incotermsDesc || vendor.buyerConditions.incotermsDesc}
                                  </TooltipContent>
                                </Tooltip>
                              </TooltipProvider>
                              {latestResponse?.vendorConditions?.incotermsCode &&
                                latestResponse.vendorConditions.incotermsCode !== vendor.buyerConditions.incotermsCode && (
                                  <Badge variant="outline" className="text-xs">변경</Badge>
                                )}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>

                  {/* 선적지 */}
                  <tr>
                    <td className="p-3 font-medium">선적지</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0];
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            {vendor.buyerConditions.placeOfShipping || "-"}
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              {latestResponse?.vendorConditions?.placeOfShipping || vendor.buyerConditions.placeOfShipping || "-"}
                              {latestResponse?.vendorConditions?.placeOfShipping &&
                                latestResponse.vendorConditions.placeOfShipping !== vendor.buyerConditions.placeOfShipping && (
                                  <Badge variant="outline" className="text-xs">변경</Badge>
                                )}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>

                  {/* 하역지 */}
                  <tr>
                    <td className="p-3 font-medium">하역지</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0];
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            {vendor.buyerConditions.placeOfDestination || "-"}
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              {latestResponse?.vendorConditions?.placeOfDestination || vendor.buyerConditions.placeOfDestination || "-"}
                              {latestResponse?.vendorConditions?.placeOfDestination &&
                                latestResponse.vendorConditions.placeOfDestination !== vendor.buyerConditions.placeOfDestination && (
                                  <Badge variant="outline" className="text-xs">변경</Badge>
                                )}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>

                  {/* 납기일 */}
                  <tr>
                    <td className="p-3 font-medium">납기일</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0];
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            {vendor.buyerConditions.deliveryDate 
                              ? format(new Date(vendor.buyerConditions.deliveryDate), "yyyy-MM-dd")
                              : "-"}
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              {latestResponse?.vendorConditions?.deliveryDate 
                                ? format(new Date(latestResponse.vendorConditions.deliveryDate), "yyyy-MM-dd")
                                : vendor.buyerConditions.deliveryDate
                                  ? format(new Date(vendor.buyerConditions.deliveryDate), "yyyy-MM-dd")
                                  : "-"}
                              {/* {latestResponse?.vendorConditions?.deliveryDate && vendor.buyerConditions.deliveryDate &&
                                new Date(latestResponse.vendorConditions.deliveryDate).getTime() !== new Date(vendor.buyerConditions.deliveryDate).getTime() && (
                                  <Badge variant="outline" className="text-xs">변경</Badge>
                                )} */}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>

                  {/* 세금조건 */}
                  <tr>
                    <td className="p-3 font-medium">세금조건</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0];
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            {vendor.buyerConditions.taxCode || "-"}
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              {latestResponse?.vendorConditions?.taxCode || vendor.buyerConditions.taxCode || "-"}
                              {latestResponse?.vendorConditions?.taxCode &&
                                latestResponse.vendorConditions.taxCode !== vendor.buyerConditions.taxCode && (
                                  <Badge variant="outline" className="text-xs">변경</Badge>
                                )}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>

                  {/* 계약기간 */}
                  <tr>
                    <td className="p-3 font-medium">계약기간</td>
                    {data.vendors.map((vendor) => {
                      const latestResponse = vendor.responses[0];
                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <td className={cn(
                            "p-3 text-center border-r",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            {vendor.buyerConditions.contractDuration || "-"}
                          </td>
                          <td className={cn(
                            "p-3 text-center",
                            vendor.isSelected && "bg-blue-50"
                          )}>
                            <div className="flex items-center justify-center gap-2">
                              {latestResponse?.vendorConditions?.contractDuration || vendor.buyerConditions.contractDuration || "-"}
                              {latestResponse?.vendorConditions?.contractDuration &&
                                latestResponse.vendorConditions.contractDuration !== vendor.buyerConditions.contractDuration && (
                                  <Badge variant="outline" className="text-xs">변경</Badge>
                                )}
                            </div>
                          </td>
                        </React.Fragment>
                      );
                    })}
                  </tr>
                </tbody>
              </table>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 품목별 상세 정보 다이얼로그 */}
      <Dialog open={showItemDetailsDialog} onOpenChange={setShowItemDetailsDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedVendorName} - {selectedResponse?.responseVersion}차 품목별 견적 상세
            </DialogTitle>
          </DialogHeader>

          {/* 응답일자 정보 */}
          {selectedResponse?.submittedAt && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground border-b pb-3">
              <Calendar className="h-4 w-4" />
              <span>
                제출일자: {format(new Date(selectedResponse.submittedAt), "yyyy년 MM월 dd일", { locale: ko })}
              </span>
            </div>
          )}

          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b bg-gray-50">
                  <th className="text-left p-3 font-semibold">품목코드</th>
                  <th className="text-left p-3 font-semibold">품목명</th>
                  <th className="text-left p-3 font-semibold">자재분류</th>
                  <th className="text-right p-3 font-semibold">수량</th>
                  <th className="text-left p-3 font-semibold">규격</th>
                  <th className="text-right p-3 font-semibold">중량</th>
                  <th className="text-right p-3 font-semibold">단가</th>
                  <th className="text-right p-3 font-semibold">총액</th>
                  <th className="text-left p-3 font-semibold">납기일자</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {selectedResponse?.quotationItems?.map((quoteItem) => {
                  const prItem = data.prItems.find(item => item.prItemId === quoteItem.prItemId);
                  if (!prItem) return null;

                  return (
                    <tr key={quoteItem.prItemId} className="hover:bg-gray-50">
                      <td className="p-3 text-sm">
                        <p className="font-medium">{prItem.materialCode}</p>
                        <p className="text-xs text-muted-foreground">
                          {prItem.prNo} • {prItem.prItem}
                        </p>
                      </td>
                      <td className="p-3">
                        <p className="font-medium">{prItem.materialDescription}</p>
                        {prItem.remark && (
                          <p className="text-xs text-muted-foreground mt-1">{prItem.remark}</p>
                        )}
                      </td>
                      <td className="p-3 text-sm">
                        {prItem.materialCategory || "-"}
                      </td>
                      <td className="p-3 text-right">
                        <p>{quoteItem.quantity} {prItem.uom}</p>
                        <p className="text-xs text-muted-foreground">요청: {prItem.requestedQuantity}</p>
                      </td>
                      <td className="p-3 text-sm">
                        {prItem.size || "-"}
                      </td>
                      <td className="p-3 text-right text-sm">
                        {prItem.grossWeight ? `${prItem.grossWeight} ${prItem.gwUom || ""}` : "-"}
                      </td>
                      <td className="p-3 text-right font-medium">
                        {formatAmount(quoteItem.unitPrice, quoteItem.currency)}
                      </td>
                      <td className="p-3 text-right font-bold">
                        {formatAmount(quoteItem.totalPrice, quoteItem.currency)}
                      </td>
                      <td className="p-3 text-sm">
                        {quoteItem.deliveryDate
                          ? format(new Date(quoteItem.deliveryDate), "yyyy-MM-dd")
                          : quoteItem.leadTime
                            ? `${quoteItem.leadTime}일`
                            : "-"}
                        {prItem.requestedDeliveryDate && (
                          <p className="text-xs text-muted-foreground">
                            요청: {format(new Date(prItem.requestedDeliveryDate), "yyyy-MM-dd")}
                          </p>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* 비고사항 */}
          {(selectedResponse?.generalRemark || selectedResponse?.technicalProposal) && (
            <div className="mt-6 pt-6 border-t">
              <h4 className="font-semibold mb-3">비고사항</h4>
              <div className="space-y-3">
                {selectedResponse.generalRemark && (
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">일반 비고:</p>
                    <p className="text-sm">{selectedResponse.generalRemark}</p>
                  </div>
                )}
                {selectedResponse.technicalProposal && (
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">기술 제안:</p>
                    <p className="text-sm">{selectedResponse.technicalProposal}</p>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* 첨부파일 */}
          {selectedResponse?.attachments && selectedResponse.attachments.length > 0 && (
            <div className="mt-6 pt-6 border-t">
              <h4 className="font-semibold mb-3 flex items-center gap-2">
                <Paperclip className="h-4 w-4" />
                제출 문서 ({selectedResponse.attachments.length}건)
              </h4>
              <div className="space-y-2">
                {selectedResponse.attachments.map((attachment) => (
                  <div 
                    key={attachment.id}
                    className="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50"
                  >
                    <div className="flex items-center gap-3 flex-1">
                      <FileText className="h-5 w-5 text-blue-500" />
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-sm truncate">
                          {attachment.originalFileName}
                        </p>
                        <div className="flex items-center gap-3 text-xs text-muted-foreground mt-1">
                          <span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded">
                            {attachment.attachmentType}
                          </span>
                          {attachment.documentNo && (
                            <span>문서번호: {attachment.documentNo}</span>
                          )}
                          {attachment.fileSize && (
                            <span>{(attachment.fileSize / 1024).toFixed(1)} KB</span>
                          )}
                          {attachment.uploadedAt && (
                            <span>
                              업로드: {format(new Date(attachment.uploadedAt), "yyyy-MM-dd HH:mm")}
                            </span>
                          )}
                        </div>
                        {attachment.description && (
                          <p className="text-xs text-muted-foreground mt-1">
                            {attachment.description}
                          </p>
                        )}
                        {(attachment.validFrom || attachment.validTo) && (
                          <p className="text-xs text-orange-600 mt-1">
                            유효기간: {attachment.validFrom ? format(new Date(attachment.validFrom), "yyyy-MM-dd") : "-"} ~ {attachment.validTo ? format(new Date(attachment.validTo), "yyyy-MM-dd") : "-"}
                          </p>
                        )}
                      </div>
                    </div>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => {
                        // 다운로드 처리
                        const link = document.createElement('a');
                        link.href = attachment.filePath;
                        link.download = attachment.originalFileName;
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                      }}
                      className="gap-1"
                    >
                      <Download className="h-3 w-3" />
                      다운로드
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>


      {/* 업체 선정 모달 */}
      {showSelectionDialog && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center">
          <div className="bg-white rounded-lg p-6 max-w-lg w-full mx-4">
            <h3 className="text-lg font-semibold mb-4">
              {hasSelection ? "업체 재선정 확인" : "업체 선정 확인"}
            </h3>

            {selectedVendorId && (() => {
              const vendor = data.vendors.find(v => v.vendorId === parseInt(selectedVendorId));
              const latestResponse = vendor?.responses[0];
              
              return (
                <div className="space-y-4">
                  <div className="rounded-lg border p-4">
                    <div className="space-y-2">
                      <div className="flex justify-between">
                        <span className="text-sm font-medium">선정 업체</span>
                        <span className="text-sm font-bold">
                          {vendor?.vendorName}
                        </span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-sm font-medium">견적 금액</span>
                        <span className="text-sm">
                          {formatAmount(
                            latestResponse?.totalAmount || 0,
                            latestResponse?.currency || "USD"
                          )}
                        </span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-sm font-medium">가격 순위</span>
                        <span className="text-sm">
                          #{latestResponse?.rank || 0}
                        </span>
                      </div>
                      {latestResponse?.conditionDifferences.hasDifferences && (
                        <Alert className="mt-2">
                          <AlertCircle className="h-4 w-4" />
                          <AlertDescription>
                            제시 조건과 차이가 있습니다. 선정 사유를 명확히 기재해주세요.
                          </AlertDescription>
                        </Alert>
                      )}
                    </div>
                  </div>

                  <div className="space-y-2">
                    <label htmlFor="selection-reason" className="text-sm font-medium">
                      선정 사유 *
                    </label>
                    <textarea
                      id="selection-reason"
                      className="w-full min-h-[100px] p-3 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="업체 선정 사유를 입력해주세요..."
                      value={selectionReason}
                      onChange={(e) => setSelectionReason(e.target.value)}
                      required
                    />
                  </div>
                </div>
              );
            })()}

            <div className="flex justify-end gap-2 mt-6">
              <Button
                variant="outline"
                onClick={() => {
                  setShowSelectionDialog(false);
                  setSelectionReason("");
                }}
                disabled={isSubmitting}
              >
                취소
              </Button>
              <Button
                onClick={handleVendorSelection}
                disabled={!selectionReason || isSubmitting}
              >
                {isSubmitting ? "처리 중..." : hasSelection ? "재선정 확정" : "선정 확정"}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 선정 취소 모달 */}
      {showCancelDialog && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center">
          <div className="bg-white rounded-lg p-6 max-w-lg w-full mx-4">
            <h3 className="text-lg font-semibold mb-4">업체 선정 취소</h3>

            <Alert className="mb-4">
              <AlertTriangle className="h-4 w-4" />
              <AlertDescription>
                업체 선정을 취소하시겠습니까? 이 작업은 되돌릴 수 없습니다.
              </AlertDescription>
            </Alert>

            {selectedVendor && (
              <div className="rounded-lg border p-4 mb-4 bg-gray-50">
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-sm font-medium">선정 업체</span>
                    <span className="text-sm font-bold">{selectedVendor.vendorName}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm font-medium">선정 금액</span>
                    <span className="text-sm">
                      {formatAmount(selectedVendor.totalAmount, selectedVendor.currency)}
                    </span>
                  </div>
                </div>
              </div>
            )}

            <div className="space-y-2">
              <label htmlFor="cancel-reason" className="text-sm font-medium">
                취소 사유 *
              </label>
              <textarea
                id="cancel-reason"
                className="w-full min-h-[100px] p-3 border rounded-md focus:outline-none focus:ring-2 focus:ring-red-500"
                placeholder="선정 취소 사유를 입력해주세요..."
                value={cancelReason}
                onChange={(e) => setCancelReason(e.target.value)}
                required
              />
            </div>

            <div className="flex justify-end gap-2 mt-6">
              <Button
                variant="outline"
                onClick={() => {
                  setShowCancelDialog(false);
                  setCancelReason("");
                }}
                disabled={isSubmitting}
              >
                닫기
              </Button>
              <Button
                variant="destructive"
                onClick={handleCancelSelection}
                disabled={!cancelReason || isSubmitting}
              >
                {isSubmitting ? "처리 중..." : "선정 취소"}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 계약 진행 모달 */}
      {showContractDialog && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center">
          <div className="bg-white rounded-lg p-6 max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-semibold mb-4">
              {selectedContractType === "PO" && "PO (SAP) 생성"}
              {selectedContractType === "CONTRACT" && "일반계약 생성"}
              {selectedContractType === "BIDDING" && "입찰 생성"}
            </h3>

            {selectedVendor && (
              <div className="space-y-4">
                <div className="rounded-lg border p-4 bg-gray-50">
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-sm font-medium">선정 업체</span>
                      <span className="text-sm font-bold">{selectedVendor.vendorName}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm font-medium">계약 금액</span>
                      <span className="text-sm">
                        {formatAmount(selectedVendor.totalAmount, selectedVendor.currency)}
                      </span>
                    </div>
                  </div>
                </div>

                <Alert>
                  <Info className="h-4 w-4" />
                  <AlertDescription>
                    {selectedContractType === "PO" && (
                      "PO를 생성하면 SAP 시스템으로 자동 전송됩니다. 계속 진행하시겠습니까?"
                    )}
                    {selectedContractType === "CONTRACT" && (
                      "일반계약을 생성하면 계약서 작성 프로세스가 시작됩니다. 계속 진행하시겠습니까?"
                    )}
                    {selectedContractType === "BIDDING" && (
                      "입찰을 생성하면 입찰 공고 프로세스가 시작됩니다. 계속 진행하시겠습니까?"
                    )}
                  </AlertDescription>
                </Alert>

                {/* 일반계약 선택 시 계약종류 및 기간 선택 */}
                {selectedContractType === "CONTRACT" && (
                  <div className="space-y-4">
                    {/* 계약종류 선택 */}
                    <div className="space-y-2">
                      <label htmlFor="contract-type" className="text-sm font-medium">
                        계약종류 선택 *
                      </label>
                      <select
                        id="contract-type"
                        className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        value={selectedGeneralContractType}
                        onChange={(e) => setSelectedGeneralContractType(e.target.value)}
                        required
                      >
                        <option value="">계약종류를 선택하세요</option>
                        {contractTypes.map(type => (
                          <option key={type.value} value={type.value}>
                            {type.label}
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* 계약 기간 */}
                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-2">
                        <label htmlFor="start-date" className="text-sm font-medium">
                          계약 시작일 *
                        </label>
                        <input
                          id="start-date"
                          type="date"
                          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          value={contractStartDate}
                          onChange={(e) => setContractStartDate(e.target.value)}
                          min={new Date().toISOString().split('T')[0]}
                          required
                        />
                      </div>

                      <div className="space-y-2">
                        <label htmlFor="end-date" className="text-sm font-medium">
                          계약 종료일 *
                        </label>
                        <input
                          id="end-date"
                          type="date"
                          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          value={contractEndDate}
                          onChange={(e) => setContractEndDate(e.target.value)}
                          min={contractStartDate || new Date().toISOString().split('T')[0]}
                          required
                        />
                      </div>
                    </div>

                    {/* 계약 기간 표시 */}
                    {contractStartDate && contractEndDate && (
                      <div className="p-3 bg-blue-50 rounded-md">
                        <p className="text-sm text-blue-700">
                          계약 기간: {format(new Date(contractStartDate), "yyyy년 MM월 dd일", { locale: ko })} ~ {format(new Date(contractEndDate), "yyyy년 MM월 dd일", { locale: ko })}
                          <span className="ml-2 font-medium">
                            ({Math.ceil((new Date(contractEndDate).getTime() - new Date(contractStartDate).getTime()) / (1000 * 60 * 60 * 24))}일간)
                          </span>
                        </p>
                      </div>
                    )}

                    {/* 계약 옵션 */}
                    <div className="space-y-2">
                      <p className="text-sm font-medium">추가 옵션</p>
                      <div className="space-y-2 text-sm">
                        <label className="flex items-center gap-2">
                          <input type="checkbox" className="rounded" />
                          <span>표준계약서 사용</span>
                        </label>
                        <label className="flex items-center gap-2">
                          <input type="checkbox" className="rounded" />
                          <span>전자서명 요청</span>
                        </label>
                        <label className="flex items-center gap-2">
                          <input type="checkbox" className="rounded" />
                          <span>자동 연장 조항 포함</span>
                        </label>
                      </div>
                    </div>
                  </div>
                )}
                {/* 입찰 옵션 */}
                {selectedContractType === "BIDDING" && (
                  <div className="space-y-4">
                    {/* 계약구분 선택 */}
                    <div className="space-y-2">
                      <label htmlFor="bidding-contract-type" className="text-sm font-medium">
                        계약구분 *
                      </label>
                      <select
                        id="bidding-contract-type"
                        className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500"
                        value={biddingContractType}
                        onChange={(e) => setBiddingContractType(e.target.value as any)}
                        required
                      >
                        <option value="">계약구분을 선택하세요</option>
                        {biddingContractTypes.map(type => (
                          <option key={type.value} value={type.value}>
                            {type.label}
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* 입찰유형 선택 */}
                    <div className="space-y-2">
                      <label htmlFor="bidding-type" className="text-sm font-medium">
                        입찰유형 *
                      </label>
                      <select
                        id="bidding-type"
                        className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500"
                        value={biddingType}
                        onChange={(e) => setBiddingType(e.target.value)}
                        required
                      >
                        <option value="">입찰유형을 선택하세요</option>
                        {biddingTypes.map(type => (
                          <option key={type.value} value={type.value}>
                            {type.label}
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* 낙찰수 선택 */}
                    <div className="space-y-2">
                      <label htmlFor="award-count" className="text-sm font-medium">
                        낙찰수
                      </label>
                      <select
                        id="award-count"
                        className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500"
                        value={awardCount}
                        onChange={(e) => setAwardCount(e.target.value as any)}
                      >
                        {awardCounts.map(type => (
                          <option key={type.value} value={type.value}>
                            {type.label}
                          </option>
                        ))}
                      </select>
                    </div>

                    {/* 입찰 기간 */}
                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-2">
                        <label htmlFor="bidding-start-date" className="text-sm font-medium">
                          입찰 시작일 *
                        </label>
                        <input
                          id="bidding-start-date"
                          type="date"
                          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500"
                          value={biddingStartDate}
                          onChange={(e) => setBiddingStartDate(e.target.value)}
                          min={new Date().toISOString().split('T')[0]}
                          required
                        />
                      </div>

                      <div className="space-y-2">
                        <label htmlFor="bidding-end-date" className="text-sm font-medium">
                          입찰 마감일 *
                        </label>
                        <input
                          id="bidding-end-date"
                          type="date"
                          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500"
                          value={biddingEndDate}
                          onChange={(e) => setBiddingEndDate(e.target.value)}
                          min={biddingStartDate || new Date().toISOString().split('T')[0]}
                          required
                        />
                      </div>
                    </div>

                    {/* 입찰 기간 표시 */}
                    {biddingStartDate && biddingEndDate && (
                      <div className="p-3 bg-purple-50 rounded-md">
                        <p className="text-sm text-purple-700">
                          입찰 기간: {format(new Date(biddingStartDate), "yyyy년 MM월 dd일", { locale: ko })} ~ {format(new Date(biddingEndDate), "yyyy년 MM월 dd일", { locale: ko })}
                          <span className="ml-2 font-medium">
                            ({Math.ceil((new Date(biddingEndDate).getTime() - new Date(biddingStartDate).getTime()) / (1000 * 60 * 60 * 24))}일간)
                          </span>
                        </p>
                      </div>
                    )}

                    {/* 추가 옵션 */}
                    <div className="space-y-2">
                      <p className="text-sm font-medium">추가 옵션</p>
                      <div className="space-y-2 text-sm">
                        <label className="flex items-center gap-2">
                          <input type="checkbox" className="rounded" />
                          <span>긴급입찰</span>
                        </label>
                        <label className="flex items-center gap-2">
                          <input type="checkbox" className="rounded" />
                          <span>사양설명회 개최</span>
                        </label>
                        <label className="flex items-center gap-2">
                          <input type="checkbox" className="rounded" />
                          <span>공개입찰</span>
                        </label>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}

            <div className="flex justify-end gap-2 mt-6">
              <Button
                variant="outline"
                onClick={() => {
                  setShowContractDialog(false);
                  // 모든 state 초기화
                  setSelectedContractType("");
                  setSelectedGeneralContractType("");
                  setContractStartDate("");
                  setContractEndDate("");
                  setBiddingContractType("unit_price");
                  setBiddingType("");
                  setAwardCount("single");
                  setBiddingStartDate("");
                  setBiddingEndDate("");
                }}
                disabled={isSubmitting}
              >
                취소
              </Button>
              <Button
                onClick={handleContractCreation}
                disabled={
                  isSubmitting ||
                  (selectedContractType === "CONTRACT" &&
                    (!selectedGeneralContractType || !contractStartDate || !contractEndDate)) ||
                  (selectedContractType === "BIDDING" &&
                    (!biddingContractType || !biddingType || !biddingStartDate || !biddingEndDate))
                }
              >
                {isSubmitting ? "처리 중..." : "진행"}
              </Button>
            </div>
          </div>
        </div>
      )}


    </div>
  );
}