"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
  Send,
  Building2,
  User,
  Calendar,
  Package,
  FileText,
  Plus,
  X,
  Paperclip,
  Download,
  Mail,
  Users,
  AlertCircle,
  Info,
  File,
  CheckCircle,
  RefreshCw,
  Phone,
  Briefcase,
  Building,
  ChevronDown,
  ChevronRight,
  UserPlus,
  Shield,
  Globe
} from "lucide-react";
import { format } from "date-fns";
import { ko } from "date-fns/locale";
import { toast } from "sonner";
import { cn, formatDate } from "@/lib/utils";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  Alert,
  AlertDescription, AlertTitle
} from "@/components/ui/alert";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/components/ui/tabs";
import { Progress } from "@/components/ui/progress";
import { getRfqEmailTemplate } from "../service";

interface ContractToGenerate {
  vendorId: number;
  vendorName: string;
  type: string;
  templateName: string;
}

// 타입 정의
interface ContactDetail {
  id: number;
  name: string;
  position?: string | null;
  department?: string | null;
  email: string;
  phone?: string | null;
  isPrimary: boolean;
}

interface CustomEmail {
  id: string;
  email: string;
  name?: string;
}

interface Vendor {
  vendorId: number;
  vendorName: string;
  vendorCode?: string | null;
  vendorCountry?: string | null;
  vendorEmail?: string | null;
  representativeEmail?: string | null;
  contacts?: ContactDetail[];
  contactsByPosition?: Record<string, ContactDetail[]>;
  primaryEmail?: string | null;
  currency?: string | null;

  // 기본계약 정보
  ndaYn?: boolean;
  generalGtcYn?: boolean;
  projectGtcYn?: boolean;
  agreementYn?: boolean;

  // 발송 정보
  sendVersion?: number;
}

interface Attachment {
  id: number;
  attachmentType: string;
  serialNo: string;
  currentRevision: string;
  description?: string;
  fileName?: string;
  fileSize?: number;
  uploadedAt?: Date;
}

interface RfqInfo {
  rfqCode: string;
  rfqTitle: string;
  rfqType: string;
  projectCode?: string;
  projectName?: string;
  picName?: string;
  picCode?: string;
  picTeam?: string;
  packageNo?: string;
  packageName?: string;
  designPicName?: string;
  designTeam?: string;
  materialGroup?: string;
  materialGroupDesc?: string;
  dueDate: Date;
  quotationType?: string;
  evaluationApply?: boolean;
  contractType?: string;

  // 추가 필드들 (HTML 템플릿에서 사용되는 변수들)
  customerName?: string;
  customerCode?: string;
  shipType?: string;
  shipClass?: string;
  shipCount?: number;
  projectFlag?: string;
  flag?: string;
  contractStartDate?: string;
  contractEndDate?: string;
  scDate?: string;
  dlDate?: string;
  itemCode?: string;
  itemName?: string;
  itemCount?: number;
  prNumber?: string;
  prIssueDate?: string;
  warrantyDescription?: string;
  repairDescription?: string;
  totalWarrantyDescription?: string;
  requiredDocuments?: string[];
  contractRequirements?: {
    hasNda: boolean;
    ndaDescription: string;
    hasGeneralGtc: boolean;
    generalGtcDescription: string;
    hasProjectGtc: boolean;
    projectGtcDescription: string;
    hasAgreement: boolean;
    agreementDescription: string;
  };
  vendorCountry?: string;
  formattedDueDate?: string;
  systemName?: string;
  hasAttachments?: boolean;
  attachmentsCount?: number;
  language?: string;
  companyName?: string;
  now?: Date;
}

interface VendorWithRecipients extends Vendor {
  selectedMainEmail: string;
  additionalEmails: string[];
  customEmails: CustomEmail[];
}

interface SendRfqDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedVendors: Vendor[];
  rfqInfo: RfqInfo;
  attachments?: Attachment[];
  onSend: (data: {
    vendors: Array<{
      vendorId: number;
      vendorName: string;
      vendorCode?: string | null;
      vendorCountry?: string | null;
      selectedMainEmail: string;
      additionalEmails: string[];
      customEmails?: Array<{ email: string; name?: string }>;
      currency?: string | null;
      contractRequirements?: {
        ndaYn: boolean;
        generalGtcYn: boolean;
        projectGtcYn: boolean;
        agreementYn: boolean;
        projectCode?: string;
      };
      isResend: boolean;
      sendVersion?: number;
      contractsSkipped?: boolean;
    }>;
    attachments: number[];
    message?: string;
    generatedPdfs?: Array<{ key: string; buffer: number[]; fileName: string }>;
    hasToSendEmail?: boolean;
  }) => Promise<{
    success: boolean;
    message: string;
    sentCount?: number;
    failedCount?: number;
    error?: string;
  }>;
}

// 이메일 유효성 검사 함수
const validateEmail = (email: string): boolean => {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email);
};

// 첨부파일 타입별 아이콘
const getAttachmentIcon = (type: string) => {
  switch (type.toLowerCase()) {
    case "technical":
      return <FileText className="h-4 w-4 text-blue-500" />;
    case "commercial":
      return <File className="h-4 w-4 text-green-500" />;
    case "drawing":
      return <Package className="h-4 w-4 text-purple-500" />;
    default:
      return <Paperclip className="h-4 w-4 text-gray-500" />;
  }
};

export function SendRfqDialog({
  open,
  onOpenChange,
  selectedVendors,
  rfqInfo,
  attachments = [],
  onSend,
}: SendRfqDialogProps) {

  const [isSending, setIsSending] = React.useState(false);
  const [vendorsWithRecipients, setVendorsWithRecipients] = React.useState<VendorWithRecipients[]>([]);
  const [selectedAttachments, setSelectedAttachments] = React.useState<number[]>([]);
  const [additionalMessage, setAdditionalMessage] = React.useState("");
  const [expandedVendors, setExpandedVendors] = React.useState<number[]>([]);
  const [customEmailInputs, setCustomEmailInputs] = React.useState<Record<number, { email: string; name: string }>>({});
  const [showCustomEmailForm, setShowCustomEmailForm] = React.useState<Record<number, boolean>>({});
  const [showResendConfirmDialog, setShowResendConfirmDialog] = React.useState(false);
  const [resendVendorsInfo, setResendVendorsInfo] = React.useState<{ count: number; names: string[] }>({ count: 0, names: [] });

  const [isGeneratingPdfs, setIsGeneratingPdfs] = React.useState(false);
  const [pdfGenerationProgress, setPdfGenerationProgress] = React.useState(0);
  const [currentGeneratingContract, setCurrentGeneratingContract] = React.useState("");
  const [generatedPdfs, setGeneratedPdfs] = React.useState<Map<string, { buffer: number[], fileName: string }>>(new Map());

  // 재전송 시 기본계약 스킵 옵션 - 업체별 관리
  const [skipContractsForVendor, setSkipContractsForVendor] = React.useState<Record<number, boolean>>({});

  // 이메일 템플릿 관련 상태
  const [activeTab, setActiveTab] = React.useState<"recipients" | "template">("recipients");
  const [selectedTemplateSlug, setSelectedTemplateSlug] = React.useState<string>("");
  const [templatePreview, setTemplatePreview] = React.useState<{ subject: string; content: string } | null>(null);
  const [isGeneratingPreview, setIsGeneratingPreview] = React.useState(false);
  const [hasToSendEmail, setHasToSendEmail] = React.useState(true); // 이메일 발송 여부

  const generateContractPdf = async (
    vendor: VendorWithRecipients,
    contractType: string,
    templateName: string
  ): Promise<{ buffer: number[], fileName: string }> => {
    try {
      // 1. 템플릿 데이터 준비 (서버 액션 호출)
      const prepareResponse = await fetch("/api/contracts/prepare-template", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          templateName,
          vendorId: vendor.vendorId,
        }),
      });

      if (!prepareResponse.ok) {
        throw new Error("템플릿 준비 실패");
      }

      const { template, templateData } = await prepareResponse.json();

      // 2. 템플릿 파일 다운로드
      const templateResponse = await fetch("/api/contracts/get-template", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ templatePath: template.filePath }),
      });

      const templateBlob = await templateResponse.blob();
      const templateFile = new window.File([templateBlob], "template.docx", {
        type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      });

      // 3. PDFtron WebViewer로 PDF 변환
      const pdfBuffer = await convertToPdfWithWebViewer(templateFile, templateData);

      const fileName = `${contractType}_${vendor.vendorCode || vendor.vendorId}_${Date.now()}.pdf`;

      return {
        buffer: Array.from(pdfBuffer), // Uint8Array를 일반 배열로 변환
        fileName
      };
    } catch (error) {
      console.error(`PDF 생성 실패 (${vendor.vendorName} - ${contractType}):`, error);
      throw error;
    }
  };

  // PDFtron WebViewer 변환 함수
  const convertToPdfWithWebViewer = async (
    templateFile: File,
    templateData: Record<string, string>
  ): Promise<Uint8Array> => {
    const { default: WebViewer } = await import("@pdftron/webviewer");

    const tempDiv = document.createElement('div');
    tempDiv.style.display = 'none';
    tempDiv.style.position = 'absolute';
    tempDiv.style.top = '-9999px';
    tempDiv.style.left = '-9999px';
    tempDiv.style.width = '1px';
    tempDiv.style.height = '1px';
    document.body.appendChild(tempDiv);

    try {
      const instance = await WebViewer(
        {
          path: "/pdftronWeb",
          licenseKey: process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY,
          fullAPI: true,
          enableOfficeEditing: true,
        },
        tempDiv
      );

      await new Promise(resolve => setTimeout(resolve, 1000));

      const { Core } = instance;
      const { createDocument } = Core;

      const templateDoc = await createDocument(templateFile, {
        filename: templateFile.name,
        extension: 'docx',
      });

      await templateDoc.applyTemplateValues(templateData);
      await new Promise(resolve => setTimeout(resolve, 3000));

      const fileData = await templateDoc.getFileData();
      const pdfBuffer = await Core.officeToPDFBuffer(fileData, { extension: 'docx' });

      instance.UI.dispose();
      return new Uint8Array(pdfBuffer);

    } finally {
      if (tempDiv.parentNode) {
        document.body.removeChild(tempDiv);
      }
    }
  };

  // 템플릿 미리보기 생성
  const generateTemplatePreview = React.useCallback(async (templateSlug: string) => {

    try {
      setIsGeneratingPreview(true);
      const template = await getRfqEmailTemplate();
      templateSlug = template?.slug || "";

      const response = await fetch('/api/email-template/preview', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          templateSlug,
          sampleData: {
            // 기본 RFQ 정보 (실제 데이터 사용)
            rfqCode: rfqInfo?.rfqCode || '',
            rfqTitle: rfqInfo?.rfqTitle || '',
            projectCode: rfqInfo?.projectCode,
            projectName: rfqInfo?.projectName,
            vendorName: "업체명 예시", // 실제로는 선택된 벤더 이름 사용
            picName: rfqInfo?.picName,
            picCode: rfqInfo?.picCode,
            picTeam: rfqInfo?.picTeam,
            dueDate: rfqInfo?.dueDate,

            // 프로젝트 관련 정보
            customerName: rfqInfo?.customerName || (rfqInfo?.projectCode ? `${rfqInfo.projectCode} 고객사` : undefined),
            customerCode: rfqInfo?.customerCode || rfqInfo?.projectCode,
            shipType: rfqInfo?.shipType || "선종 정보",
            shipClass: rfqInfo?.shipClass || "선급 정보",
            shipCount: rfqInfo?.shipCount || 1,
            projectFlag: rfqInfo?.projectFlag || "KR",
            flag: rfqInfo?.flag || "한국",
            contractStartDate: rfqInfo?.contractStartDate || new Date().toISOString().split('T')[0],
            contractEndDate: rfqInfo?.contractEndDate || new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
            scDate: rfqInfo?.scDate || new Date().toISOString().split('T')[0],
            dlDate: rfqInfo?.dlDate || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],

            // 패키지/자재 정보
            packageNo: rfqInfo?.packageNo,
            packageName: rfqInfo?.packageName,
            materialGroup: rfqInfo?.materialGroup,
            materialGroupDesc: rfqInfo?.materialGroupDesc,

            // 품목 정보
            itemCode: rfqInfo?.itemCode || "품목코드",
            itemName: rfqInfo?.itemName || "품목명",
            itemCount: rfqInfo?.itemCount || 1,
            prNumber: rfqInfo?.prNumber || "PR-001",
            prIssueDate: rfqInfo?.prIssueDate || new Date().toISOString().split('T')[0],

            // 보증 정보
            warrantyDescription: rfqInfo?.warrantyDescription || "제조사의 표준 보증 조건 적용",
            repairDescription: rfqInfo?.repairDescription || "하자 발생 시 무상 수리",
            totalWarrantyDescription: rfqInfo?.totalWarrantyDescription || "전체 품목에 대한 보증 적용",

            // 필요 문서
            requiredDocuments: rfqInfo?.requiredDocuments || [
              "상세 견적서",
              "납기 계획서",
              "품질 보증서",
              "기술 사양서"
            ],

            // 계약 요구사항
            contractRequirements: rfqInfo?.contractRequirements || {
              hasNda: true,
              ndaDescription: "NDA (비밀유지계약)",
              hasGeneralGtc: true,
              generalGtcDescription: "General GTC",
              hasProjectGtc: !!rfqInfo?.projectCode,
              projectGtcDescription: `Project GTC (${rfqInfo?.projectCode || ''})`,
              hasAgreement: false,
              agreementDescription: "기술 자료 제공 동의서"
            },

            // 벤더 정보
            vendorCountry: rfqInfo?.vendorCountry || "한국",

            // 시스템 정보
            formattedDueDate: rfqInfo?.formattedDueDate || (rfqInfo?.dueDate ? new Date(rfqInfo.dueDate).toLocaleDateString('ko-KR') : ''),
            systemName: rfqInfo?.systemName || "SHI EVCP",
            hasAttachments: rfqInfo?.hasAttachments || false,
            attachmentsCount: rfqInfo?.attachmentsCount || 0,

            // 언어 설정
            language: rfqInfo?.language || "ko",

            // 회사 정보 (t helper 대체용)
            companyName: "삼성중공업",
            email: "삼성중공업",

            // 현재 시간
            now: new Date(),

            // 기타 정보
            designPicName: rfqInfo?.designPicName,
            designTeam: rfqInfo?.designTeam,
            quotationType: rfqInfo?.quotationType,
            evaluationApply: rfqInfo?.evaluationApply,
            contractType: rfqInfo?.contractType
          }
        })
      });

      const data = await response.json();

      if (data.success) {
        setTemplatePreview({
          subject: data.subject || '',
          content: data.html || ''
        });
      } else {
        console.error('미리보기 생성 실패:', data.error);
        setTemplatePreview(null);
      }
    } catch (error) {
      console.error('미리보기 생성 실패:', error);
      setTemplatePreview(null);
    } finally {
      setIsGeneratingPreview(false);
    }
  }, [rfqInfo]);

  // 초기화
  React.useEffect(() => {
    if (open && selectedVendors.length > 0) {
      setVendorsWithRecipients(
        selectedVendors.map(v => ({
          ...v,
          selectedMainEmail: v.primaryEmail || v.vendorEmail || '',
          additionalEmails: [],
          customEmails: []
        }))
      );
      // 모든 첨부파일 선택
      setSelectedAttachments(attachments.map(a => a.id));
      // 첫 번째 벤더를 자동으로 확장
      if (selectedVendors.length > 0) {
        setExpandedVendors([selectedVendors[0].vendorId]);
      }
      // 초기화
      setCustomEmailInputs({});
      setShowCustomEmailForm({});

      // 재전송 업체들의 기본계약 스킵 옵션 초기화 (기본값: false - 재생성)
      const skipOptions: Record<number, boolean> = {};
      selectedVendors.forEach(v => {
        if (v.sendVersion && v.sendVersion > 0) {
          skipOptions[v.vendorId] = false; // 기본값은 재생성
        }
      });
      setSkipContractsForVendor(skipOptions);
    }
  }, [open, selectedVendors, attachments]);

  // 커스텀 이메일 추가
  const addCustomEmail = (vendorId: number) => {
    const input = customEmailInputs[vendorId];
    if (!input || !input.email) {
      toast.error("이메일 주소를 입력해주세요.");
      return;
    }

    if (!validateEmail(input.email)) {
      toast.error("올바른 이메일 형식이 아닙니다.");
      return;
    }

    setVendorsWithRecipients(prev =>
      prev.map(v => {
        if (v.vendorId !== vendorId) return v;

        // 중복 체크
        const allEmails = [
          v.vendorEmail,
          v.representativeEmail,
          ...(v.contacts?.map(c => c.email) || []),
          ...v.customEmails.map(c => c.email)
        ].filter(Boolean);

        if (allEmails.includes(input.email)) {
          toast.error("이미 등록된 이메일 주소입니다.");
          return v;
        }

        const newCustomEmail: CustomEmail = {
          id: `custom-${Date.now()}`,
          email: input.email,
          name: input.name || input.email.split('@')[0]
        };

        return {
          ...v,
          customEmails: [...v.customEmails, newCustomEmail]
        };
      })
    );

    // 입력 필드 초기화
    setCustomEmailInputs(prev => ({
      ...prev,
      [vendorId]: { email: '', name: '' }
    }));
    setShowCustomEmailForm(prev => ({
      ...prev,
      [vendorId]: false
    }));

    toast.success("수신자가 추가되었습니다.");
  };

  // 커스텀 이메일 삭제
  const removeCustomEmail = (vendorId: number, emailId: string) => {
    setVendorsWithRecipients(prev =>
      prev.map(v => {
        if (v.vendorId !== vendorId) return v;

        const emailToRemove = v.customEmails.find(e => e.id === emailId);
        if (!emailToRemove) return v;

        return {
          ...v,
          customEmails: v.customEmails.filter(e => e.id !== emailId),
          // 만약 삭제하는 이메일이 선택된 주 수신자라면 초기화
          selectedMainEmail: v.selectedMainEmail === emailToRemove.email ? '' : v.selectedMainEmail,
          // 추가 수신자에서도 제거
          additionalEmails: v.additionalEmails.filter(e => e !== emailToRemove.email)
        };
      })
    );
  };

  // 주 수신자 이메일 변경
  const handleMainEmailChange = (vendorId: number, email: string) => {
    setVendorsWithRecipients(prev =>
      prev.map(v =>
        v.vendorId === vendorId
          ? { ...v, selectedMainEmail: email }
          : v
      )
    );
  };

  // 추가 수신자 토글
  const toggleAdditionalEmail = (vendorId: number, email: string) => {
    setVendorsWithRecipients(prev =>
      prev.map(v => {
        if (v.vendorId !== vendorId) return v;

        const additionalEmails = v.additionalEmails.includes(email)
          ? v.additionalEmails.filter(e => e !== email)
          : [...v.additionalEmails, email];

        return { ...v, additionalEmails };
      })
    );
  };

  // 벤더 확장/축소 토글
  const toggleVendorExpand = (vendorId: number) => {
    setExpandedVendors(prev =>
      prev.includes(vendorId)
        ? prev.filter(id => id !== vendorId)
        : [...prev, vendorId]
    );
  };

  // 첨부파일 선택 토글
  const toggleAttachment = (attachmentId: number) => {
    setSelectedAttachments(prev =>
      prev.includes(attachmentId)
        ? prev.filter(id => id !== attachmentId)
        : [...prev, attachmentId]
    );
  };

  // 실제 발송 처리 함수 (재발송 확인 후 또는 바로 실행)
  const proceedWithSend = React.useCallback(async () => {
    try {
      setIsSending(true);

      // 기본계약이 필요한 계약서 목록 수집
      const contractsToGenerate: ContractToGenerate[] = [];

      for (const vendor of vendorsWithRecipients) {
        // 재전송 업체이고 해당 업체의 스킵 옵션이 켜져 있으면 계약서 생성 건너뛰기
        const isResendVendor = vendor.sendVersion && vendor.sendVersion > 0;
        if (isResendVendor && skipContractsForVendor[vendor.vendorId]) {
          continue; // 이 벤더의 계약서 생성을 스킵
        }

        if (vendor.ndaYn) {
          contractsToGenerate.push({
            vendorId: vendor.vendorId,
            vendorName: vendor.vendorName,
            type: "NDA",
            templateName: "비밀"
          });
        }
        if (vendor.generalGtcYn) {
          contractsToGenerate.push({
            vendorId: vendor.vendorId,
            vendorName: vendor.vendorName,
            type: "General_GTC",
            templateName: "General GTC"
          });
        }
        if (vendor.projectGtcYn && rfqInfo?.projectCode) {
          contractsToGenerate.push({
            vendorId: vendor.vendorId,
            vendorName: vendor.vendorName,
            type: "Project_GTC",
            templateName: rfqInfo.projectCode
          });
        }
        if (vendor.agreementYn) {
          contractsToGenerate.push({
            vendorId: vendor.vendorId,
            vendorName: vendor.vendorName,
            type: "기술자료",
            templateName: "기술"
          });
        }
      }

      let pdfsMap = new Map<string, { buffer: number[], fileName: string }>();

      // PDF 생성이 필요한 경우
      if (contractsToGenerate.length > 0) {
        setIsGeneratingPdfs(true);
        setPdfGenerationProgress(0);

        try {
          let completed = 0;

          for (const contract of contractsToGenerate) {
            setCurrentGeneratingContract(`${contract.vendorName} - ${contract.type}`);

            const vendor = vendorsWithRecipients.find(v => v.vendorId === contract.vendorId);
            if (!vendor) continue;

            const pdf = await generateContractPdf(vendor, contract.type, contract.templateName);
            pdfsMap.set(`${contract.vendorId}_${contract.type}_${contract.templateName}`, pdf);

            completed++;
            setPdfGenerationProgress((completed / contractsToGenerate.length) * 100);

            await new Promise(resolve => setTimeout(resolve, 100));
          }

          setGeneratedPdfs(pdfsMap);  // UI 업데이트용
        } catch (error) {
          console.error("PDF 생성 실패:", error);
          toast.error("기본계약서 생성에 실패했습니다.");
          setIsGeneratingPdfs(false);
          setPdfGenerationProgress(0);
          return;
        }
      }

      // RFQ 발송 - pdfsMap을 직접 사용
      setIsGeneratingPdfs(false);
      setIsSending(true);

      const sendResult = await onSend({
        vendors: vendorsWithRecipients.map(v => ({
          vendorId: v.vendorId,
          vendorName: v.vendorName,
          vendorCode: v.vendorCode,
          vendorCountry: v.vendorCountry,
          selectedMainEmail: v.selectedMainEmail,
          additionalEmails: v.additionalEmails,
          customEmails: v.customEmails.map(c => ({ email: c.email, name: c.name })),
          currency: v.currency,
          contractRequirements: {
            ndaYn: v.ndaYn || false,
            generalGtcYn: v.generalGtcYn || false,
            projectGtcYn: v.projectGtcYn || false,
            agreementYn: v.agreementYn || false,
            projectCode: v.projectGtcYn ? rfqInfo?.projectCode : undefined,
          },
          isResend: (v.sendVersion || 0) > 0,
          sendVersion: v.sendVersion,
          contractsSkipped: ((v.sendVersion || 0) > 0) && skipContractsForVendor[v.vendorId],
        })),
        attachments: selectedAttachments,
        message: additionalMessage,
        // 생성된 PDF 데이터 추가
        generatedPdfs: Array.from(pdfsMap.entries()).map(([key, data]) => ({
          key,
          ...data
        })),
        // 이메일 발송 처리 (사용자 선택에 따라)
        hasToSendEmail: hasToSendEmail,
      });

      if (!sendResult.success) {
        throw new Error(sendResult.message);
      }

      toast.success(sendResult.message);
      onOpenChange(false);

    } catch (error) {
      console.error("RFQ 발송 실패:", error);
      toast.error("RFQ 발송에 실패했습니다.");
    } finally {
      setIsSending(false);
      setIsGeneratingPdfs(false);
      setPdfGenerationProgress(0);
      setCurrentGeneratingContract("");
      setSkipContractsForVendor({}); // 초기화
    }
  }, [vendorsWithRecipients, selectedAttachments, additionalMessage, onSend, onOpenChange, rfqInfo, skipContractsForVendor, hasToSendEmail]);

  // 전송 처리
  const handleSend = async () => {
    try {
      // 유효성 검사
      const vendorsWithoutEmail = vendorsWithRecipients.filter(v => !v.selectedMainEmail);
      if (vendorsWithoutEmail.length > 0) {
        toast.error(`${vendorsWithoutEmail.map(v => v.vendorName).join(', ')}의 주 수신자를 선택해주세요.`);
        return;
      }

      // 첨부파일은 선택사항 - 없어도 발송 가능

      // 재발송 업체 확인
      const resendVendors = vendorsWithRecipients.filter(v => v.sendVersion && v.sendVersion > 0);
      if (resendVendors.length > 0) {
        // AlertDialog를 표시하기 위해 상태 설정
        setResendVendorsInfo({
          count: resendVendors.length,
          names: resendVendors.map(v => v.vendorName)
        });
        setShowResendConfirmDialog(true);
        return; // 여기서 일단 중단하고 다이얼로그 응답을 기다림
      }

      // 재발송 업체가 없으면 바로 진행
      await proceedWithSend();
    } catch (error) {
      console.error("RFQ 발송 준비 실패:", error);
      toast.error("RFQ 발송 준비에 실패했습니다.");
    }
  };

  // 총 수신자 수 계산
  const totalRecipientCount = React.useMemo(() => {
    return vendorsWithRecipients.reduce((acc, v) =>
      acc + 1 + v.additionalEmails.length, 0
    );
  }, [vendorsWithRecipients]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-5xl max-h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Send className="h-5 w-5" />
            RFQ 일괄 발송
          </DialogTitle>
          <DialogDescription>
            선택한 {selectedVendors.length}개 업체에 RFQ를 발송합니다.
          </DialogDescription>
        </DialogHeader>

        {/* 탭 구조 */}
        <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as "recipients" | "template")} className="flex-1 flex flex-col">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="recipients">수신자 설정</TabsTrigger>
            <TabsTrigger value="template">이메일 템플릿</TabsTrigger>
          </TabsList>

          <div className="flex-1 overflow-y-auto px-1 mt-4" style={{ maxHeight: 'calc(90vh - 240px)' }}>
            <TabsContent value="recipients" className="mt-0 space-y-6 pr-4">
            {/* 재발송 경고 메시지 - 재발송 업체가 있을 때만 표시 */}
            {vendorsWithRecipients.some(v => v.sendVersion && v.sendVersion > 0) && (
              <Alert className="border-yellow-500 bg-yellow-50">
                <AlertCircle className="h-4 w-4 text-yellow-600" />
                <AlertTitle className="text-yellow-800">재발송 경고</AlertTitle>
                <AlertDescription className="text-yellow-700 space-y-3">
                  <ul className="list-disc list-inside space-y-1">
                    <li>재발송 대상 업체의 기존 견적 데이터가 초기화됩니다.</li>
                    <li>업체는 새로운 버전의 견적서를 작성해야 합니다.</li>
                    <li>이전에 제출한 견적서는 더 이상 유효하지 않습니다.</li>
                  </ul>

                  {/* 기본계약 재발송 정보 */}
                  <div className="mt-3 pt-3 border-t border-yellow-400">
                    <div className="space-y-2">
                      <p className="text-sm font-medium flex items-center gap-2">
                        <FileText className="h-4 w-4" />
                        기본계약서 재발송 설정
                      </p>
                      <p className="text-xs text-yellow-600">
                        각 재발송 업체별로 기본계약서 재생성 여부를 선택할 수 있습니다.
                        아래 표에서 업체별로 설정해주세요.
                      </p>
                    </div>
                  </div>
                </AlertDescription>
              </Alert>
            )}

            {/* RFQ 정보 섹션 */}
            <div className="space-y-4">
              <div className="flex items-center gap-2 text-sm font-medium">
                <Info className="h-4 w-4" />
                RFQ 정보
              </div>

              <div className="bg-muted/50 rounded-lg p-4 space-y-3">
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground min-w-[80px]">RFQ 코드:</span>
                    <span className="font-medium">{rfqInfo?.rfqCode}</span>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground min-w-[80px]">견적마감일:</span>
                    <span className="font-medium text-red-600">
                      {formatDate(rfqInfo?.dueDate, "KR")}
                    </span>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground min-w-[80px]">프로젝트:</span>
                    <span className="font-medium">
                      {rfqInfo?.projectCode} ({rfqInfo?.projectName})
                    </span>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground min-w-[80px]"> 자재그룹:</span>
                    <span className="font-medium">
                      {rfqInfo?.packageNo} - {rfqInfo?.packageName}
                    </span>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground min-w-[80px]">구매담당자:</span>
                    <span className="font-medium">
                      {rfqInfo?.picName} ({rfqInfo?.picCode}) {rfqInfo?.picTeam}
                    </span>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-muted-foreground min-w-[80px]"> 설계담당자:</span>
                    <span className="font-medium">
                      {rfqInfo?.designPicName}
                    </span>
                  </div>
                  {rfqInfo?.rfqCode.startsWith("F") &&
                    <>
                      <div className="flex items-start gap-2">
                        <span className="text-muted-foreground min-w-[80px]">견적명:</span>
                        <span className="font-medium">
                          {rfqInfo?.rfqTitle}
                        </span>
                      </div>
                      <div className="flex items-start gap-2">
                        <span className="text-muted-foreground min-w-[80px]"> 견적종류:</span>
                        <span className="font-medium">
                          {rfqInfo?.rfqType}
                        </span>
                      </div>
                    </>
                  }
                </div>
              </div>
            </div>

            <Separator />

            {/* 수신 업체 섹션 - 테이블 버전 with 인라인 추가 폼 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 text-sm font-medium">
                  <Building2 className="h-4 w-4" />
                  수신 업체 ({selectedVendors.length})
                </div>
                <Badge variant="outline" className="flex items-center gap-1">
                  <Users className="h-3 w-3" />
                  총 {totalRecipientCount}명
                </Badge>
              </div>

              <div className="border rounded-lg overflow-hidden">
                <table className="w-full">
                  <thead className="bg-muted/50 border-b">
                    <tr>
                      <th className="text-left p-2 text-xs font-medium">No.</th>
                      <th className="text-left p-2 text-xs font-medium">업체명</th>
                      <th className="text-left p-2 text-xs font-medium">기본계약</th>
                      <th className="text-left p-2 text-xs font-medium">
                        <div className="flex items-center gap-2">
                          <span>계약서 재발송</span>
                          {vendorsWithRecipients.some(v => v.sendVersion && v.sendVersion > 0) && (
                            <TooltipProvider>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="h-5 px-1 text-xs"
                                    onClick={() => {
                                      const resendVendors = vendorsWithRecipients.filter(v => v.sendVersion && v.sendVersion > 0);
                                      const allChecked = resendVendors.every(v => !skipContractsForVendor[v.vendorId]);
                                      const newSkipOptions: Record<number, boolean> = {};
                                      resendVendors.forEach(v => {
                                        newSkipOptions[v.vendorId] = allChecked;
                                      });
                                      setSkipContractsForVendor(newSkipOptions);
                                    }}
                                  >
                                    {Object.values(skipContractsForVendor).every(v => v) ? "전체 재생성" :
                                      Object.values(skipContractsForVendor).every(v => !v) ? "전체 유지" : "전체 유지"}
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent>
                                  재발송 업체 전체 선택/해제
                                </TooltipContent>
                              </Tooltip>
                            </TooltipProvider>
                          )}
                        </div>
                      </th>
                      <th className="text-left p-2 text-xs font-medium">주 수신자</th>
                      <th className="text-left p-2 text-xs font-medium">CC</th>
                      <th className="text-left p-2 text-xs font-medium">작업</th>
                    </tr>
                  </thead>
                  <tbody>
                    {vendorsWithRecipients.map((vendor, index) => {
                      const allContacts = vendor.contacts || [];
                      const allEmails = [
                        ...(vendor.representativeEmail ? [{
                          value: vendor.representativeEmail,
                          label: '대표자',
                          email: vendor.representativeEmail,
                          type: 'representative'
                        }] : []),
                        ...allContacts.map(c => ({
                          value: c.email,
                          label: `${c.name} ${c.position ? `(${c.position})` : ''}`,
                          email: c.email,
                          type: 'contact'
                        })),
                        ...vendor.customEmails.map(c => ({
                          value: c.email,
                          label: c.name || c.email,
                          email: c.email,
                          type: 'custom'
                        })),
                        ...(vendor.vendorEmail && vendor.vendorEmail !== vendor.representativeEmail ? [{
                          value: vendor.vendorEmail,
                          label: '업체 기본',
                          email: vendor.vendorEmail,
                          type: 'default'
                        }] : [])
                      ];

                      const ccEmails = allEmails.filter(e => e.value !== vendor.selectedMainEmail);
                      const selectedMainEmailInfo = allEmails.find(e => e.value === vendor.selectedMainEmail);
                      const isFormOpen = showCustomEmailForm[vendor.vendorId];
                      const isResend = vendor.sendVersion && vendor.sendVersion > 0;

                      // 기본계약 요구사항 확인
                      const contracts = [];
                      if (vendor.ndaYn) contracts.push({ name: "NDA", icon: <Shield className="h-3 w-3" /> });
                      if (vendor.generalGtcYn) contracts.push({ name: "General GTC", icon: <Globe className="h-3 w-3" /> });
                      if (vendor.projectGtcYn) contracts.push({ name: "Project GTC", icon: <Building className="h-3 w-3" /> });
                      if (vendor.agreementYn) contracts.push({ name: "기술자료", icon: <FileText className="h-3 w-3" /> });

                      return (
                        <React.Fragment key={vendor.vendorId}>
                          <tr className="border-b hover:bg-muted/20">
                            <td className="p-2">
                              <div className="flex items-center gap-1">
                                <div className="flex items-center justify-center w-5 h-5 rounded-full bg-primary/10 text-primary text-xs font-medium">
                                  {index + 1}
                                </div>
                                {isResend && (
                                  <TooltipProvider>
                                    <Tooltip>
                                      <TooltipTrigger>
                                        <Badge variant="warning" className="text-xs">
                                          재발송
                                        </Badge>
                                      </TooltipTrigger>
                                      <TooltipContent>
                                        <div className="space-y-1">
                                          <p className="font-semibold">⚠️ 재발송 경고</p>
                                          <p className="text-xs">발송 회차: {vendor.sendVersion + 1}회차</p>
                                          <p className="text-xs text-yellow-600">기존 견적 데이터가 초기화됩니다</p>
                                        </div>
                                      </TooltipContent>
                                    </Tooltip>
                                  </TooltipProvider>
                                )}
                              </div>
                            </td>
                            <td className="p-2">
                              <div className="space-y-1">
                                <div className="font-medium text-sm">{vendor.vendorName}</div>
                                <div className="flex items-center gap-1">
                                  <Badge variant="outline" className="text-xs">
                                    {vendor.vendorCountry}
                                  </Badge>
                                  <span className="text-xs text-muted-foreground">
                                    {vendor.vendorCode}
                                  </span>
                                </div>
                              </div>
                            </td>
                            <td className="p-2">
                              {contracts.length > 0 ? (
                                <div className="flex flex-wrap gap-1">
                                  {/* 재전송이고 스킵 옵션이 켜져 있으면 표시 */}
                                  {isResend && skipContractsForVendor[vendor.vendorId] ? (
                                    <Badge variant="secondary" className="text-xs px-1">
                                      <CheckCircle className="h-3 w-3 mr-1 text-green-500" />
                                      <span>기존 계약서 유지</span>
                                    </Badge>
                                  ) : (
                                    contracts.map((contract, idx) => (
                                      <TooltipProvider key={idx}>
                                        <Tooltip>
                                          <TooltipTrigger>
                                            <Badge variant="outline" className="text-xs px-1">
                                              {contract.icon}
                                              <span className="ml-1">{contract.name}</span>
                                              {isResend && !skipContractsForVendor[vendor.vendorId] && (
                                                <RefreshCw className="h-3 w-3 ml-1 text-orange-500" />
                                              )}
                                            </Badge>
                                          </TooltipTrigger>
                                          <TooltipContent>
                                            <p className="text-xs">
                                              {contract.name === "NDA" && "비밀유지 계약서 요청"}
                                              {contract.name === "General GTC" && "일반 거래약관 요청"}
                                              {contract.name === "Project GTC" && `프로젝트 거래약관 요청 (${rfqInfo?.projectCode})`}
                                              {contract.name === "기술자료" && "기술자료 제공 동의서 요청"}
                                              {isResend && !skipContractsForVendor[vendor.vendorId] && (
                                                <span className="block mt-1 text-orange-400">⚠️ 재생성됨</span>
                                              )}
                                            </p>
                                          </TooltipContent>
                                        </Tooltip>
                                      </TooltipProvider>
                                    ))
                                  )}
                                </div>
                              ) : (
                                <span className="text-xs text-muted-foreground">없음</span>
                              )}
                            </td>
                            <td className="p-2">
                              {isResend && contracts.length > 0 ? (
                                <div className="flex items-center justify-center">
                                  <TooltipProvider>
                                    <Tooltip>
                                      <TooltipTrigger asChild>
                                        <div className="flex items-center gap-2">
                                          <Checkbox
                                            checked={!skipContractsForVendor[vendor.vendorId]}
                                            onCheckedChange={(checked) => {
                                              setSkipContractsForVendor(prev => ({
                                                ...prev,
                                                [vendor.vendorId]: !checked
                                              }));
                                            }}
                                          // className="data-[state=checked]:bg-orange-600 data-[state=checked]:border-orange-600"
                                          />
                                          <span className="text-xs">
                                            {skipContractsForVendor[vendor.vendorId] ? "유지" : "재생성"}
                                          </span>
                                        </div>
                                      </TooltipTrigger>
                                      <TooltipContent>
                                        <p className="text-xs">
                                          {skipContractsForVendor[vendor.vendorId]
                                            ? "기존 계약서를 그대로 유지합니다"
                                            : "기존 계약서를 삭제하고 새로 생성합니다"}
                                        </p>
                                      </TooltipContent>
                                    </Tooltip>
                                  </TooltipProvider>
                                </div>
                              ) : (
                                <span className="text-xs text-muted-foreground text-center block">
                                  {isResend ? "계약서 없음" : "-"}
                                </span>
                              )}
                            </td>
                            <td className="p-2">
                              <Select
                                value={vendor.selectedMainEmail}
                                onValueChange={(value) => handleMainEmailChange(vendor.vendorId, value)}
                              >
                                <SelectTrigger className="h-7 text-xs w-[200px]">
                                  <SelectValue placeholder="선택하세요">
                                    {selectedMainEmailInfo && (
                                      <div className="flex items-center gap-1">
                                        {selectedMainEmailInfo.type === 'representative' && <Building2 className="h-3 w-3" />}
                                        {selectedMainEmailInfo.type === 'custom' && <UserPlus className="h-3 w-3 text-green-500" />}
                                        <span className="truncate">{selectedMainEmailInfo.label}</span>
                                      </div>
                                    )}
                                  </SelectValue>
                                </SelectTrigger>
                                <SelectContent>
                                  {allEmails.map((email) => (
                                    <SelectItem key={email.value} value={email.value} className="text-xs">
                                      <div className="flex items-center gap-1">
                                        {email.type === 'representative' && <Building2 className="h-3 w-3" />}
                                        {email.type === 'custom' && <UserPlus className="h-3 w-3 text-green-500" />}
                                        <span>{email.label}</span>
                                      </div>
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                              {!vendor.selectedMainEmail && (
                                <span className="text-xs text-red-500">필수</span>
                              )}
                            </td>
                            <td className="p-2">
                              <Popover>
                                <PopoverTrigger asChild>
                                  <Button variant="outline" className="h-7 text-xs">
                                    {vendor.additionalEmails.length > 0
                                      ? `${vendor.additionalEmails.length}명`
                                      : "선택"
                                    }
                                    <ChevronDown className="ml-1 h-3 w-3" />
                                  </Button>
                                </PopoverTrigger>
                                <PopoverContent className="w-48 p-2">
                                  <div className="max-h-48 overflow-y-auto space-y-1">
                                    {ccEmails.map((email) => (
                                      <div key={email.value} className="flex items-center space-x-1 p-1">
                                        <Checkbox
                                          checked={vendor.additionalEmails.includes(email.value)}
                                          onCheckedChange={() => toggleAdditionalEmail(vendor.vendorId, email.value)}
                                          className="h-3 w-3"
                                        />
                                        <label className="text-xs cursor-pointer flex-1 truncate">
                                          {email.label}
                                        </label>
                                      </div>
                                    ))}
                                  </div>
                                </PopoverContent>
                              </Popover>
                            </td>
                            <td className="p-2">
                              <div className="flex items-center gap-1">
                                <TooltipProvider>
                                  <Tooltip>
                                    <TooltipTrigger asChild>
                                      <Button
                                        variant={isFormOpen ? "default" : "ghost"}
                                        size="sm"
                                        className="h-6 w-6 p-0"
                                        onClick={() => {
                                          setShowCustomEmailForm(prev => ({
                                            ...prev,
                                            [vendor.vendorId]: !prev[vendor.vendorId]
                                          }));
                                        }}
                                      >
                                        {isFormOpen ? <X className="h-3 w-3" /> : <Plus className="h-3 w-3" />}
                                      </Button>
                                    </TooltipTrigger>
                                    <TooltipContent>{isFormOpen ? "닫기" : "수신자 추가"}</TooltipContent>
                                  </Tooltip>
                                </TooltipProvider>
                                {vendor.customEmails.length > 0 && (
                                  <Badge variant="success" className="text-xs">
                                    +{vendor.customEmails.length}
                                  </Badge>
                                )}
                              </div>
                            </td>
                          </tr>

                          {/* 인라인 수신자 추가 폼 - 한 줄 레이아웃 */}
                          {isFormOpen && (
                            <tr className="bg-muted/10 border-b">
                              <td colSpan={7} className="p-4">
                                <div className="space-y-3">
                                  <div className="flex items-center justify-between mb-2">
                                    <div className="flex items-center gap-2 text-sm font-medium">
                                      <UserPlus className="h-4 w-4" />
                                      수신자 추가 - {vendor.vendorName}
                                    </div>
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="h-6 w-6 p-0"
                                      onClick={() => setShowCustomEmailForm(prev => ({
                                        ...prev,
                                        [vendor.vendorId]: false
                                      }))}
                                    >
                                      <X className="h-3 w-3" />
                                    </Button>
                                  </div>

                                  {/* 한 줄에 모든 요소 배치 - 명확한 너비 지정 */}
                                  <div className="flex gap-2 items-end">
                                    <div className="w-[150px]">
                                      <Label className="text-xs mb-1 block">이름 (선택)</Label>
                                      <Input
                                        placeholder="홍길동"
                                        className="h-8 text-sm"
                                        value={customEmailInputs[vendor.vendorId]?.name || ''}
                                        onChange={(e) => setCustomEmailInputs(prev => ({
                                          ...prev,
                                          [vendor.vendorId]: {
                                            ...prev[vendor.vendorId],
                                            name: e.target.value
                                          }
                                        }))}
                                      />
                                    </div>
                                    <div className="flex-1">
                                      <Label className="text-xs mb-1 block">이메일 <span className="text-red-500">*</span></Label>
                                      <Input
                                        type="email"
                                        placeholder="example@company.com"
                                        className="h-8 text-sm"
                                        value={customEmailInputs[vendor.vendorId]?.email || ''}
                                        onChange={(e) => setCustomEmailInputs(prev => ({
                                          ...prev,
                                          [vendor.vendorId]: {
                                            ...prev[vendor.vendorId],
                                            email: e.target.value
                                          }
                                        }))}
                                        onKeyPress={(e) => {
                                          if (e.key === 'Enter') {
                                            e.preventDefault();
                                            addCustomEmail(vendor.vendorId);
                                          }
                                        }}
                                      />
                                    </div>
                                    <Button
                                      size="sm"
                                      className="h-8 px-4"
                                      onClick={() => addCustomEmail(vendor.vendorId)}
                                      disabled={!customEmailInputs[vendor.vendorId]?.email}
                                    >
                                      <Plus className="h-3 w-3 mr-1" />
                                      추가
                                    </Button>
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      className="h-8 px-4"
                                      onClick={() => {
                                        setCustomEmailInputs(prev => ({
                                          ...prev,
                                          [vendor.vendorId]: { email: '', name: '' }
                                        }));
                                        setShowCustomEmailForm(prev => ({
                                          ...prev,
                                          [vendor.vendorId]: false
                                        }));
                                      }}
                                    >
                                      취소
                                    </Button>
                                  </div>

                                  {/* 추가된 커스텀 이메일 목록 */}
                                  {vendor.customEmails.length > 0 && (
                                    <div className="mt-3 pt-3 border-t">
                                      <div className="text-xs text-muted-foreground mb-2">추가된 수신자 목록</div>
                                      <div className="grid grid-cols-2 xl:grid-cols-3 gap-2">
                                        {vendor.customEmails.map((custom) => (
                                          <div key={custom.id} className="flex items-center justify-between bg-background rounded-md p-2">
                                            <div className="flex items-center gap-2 min-w-0">
                                              <UserPlus className="h-3 w-3 text-green-500 flex-shrink-0" />
                                              <div className="min-w-0">
                                                <div className="text-sm font-medium truncate">{custom.name}</div>
                                                <div className="text-xs text-muted-foreground truncate">{custom.email}</div>
                                              </div>
                                            </div>
                                            <Button
                                              variant="ghost"
                                              size="sm"
                                              className="h-6 w-6 p-0 flex-shrink-0"
                                              onClick={() => removeCustomEmail(vendor.vendorId, custom.id)}
                                            >
                                              <X className="h-3 w-3" />
                                            </Button>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              </td>
                            </tr>
                          )}
                        </React.Fragment>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>


            <Separator />
            {/* 첨부파일 섹션 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 text-sm font-medium">
                  <Paperclip className="h-4 w-4" />
                  첨부파일 ({selectedAttachments.length}/{attachments.length})
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    if (selectedAttachments.length === attachments.length) {
                      setSelectedAttachments([]);
                    } else {
                      setSelectedAttachments(attachments.map(a => a.id));
                    }
                  }}
                >
                  {selectedAttachments.length === attachments.length ? "전체 해제" : "전체 선택"}
                </Button>
              </div>

              <div className="border rounded-lg divide-y max-h-40 overflow-y-auto">
                {attachments.length > 0 ? (
                  attachments.map((attachment) => (
                    <div
                      key={attachment.id}
                      className="flex items-center justify-between p-2 hover:bg-muted/50 transition-colors"
                    >
                      <div className="flex items-center gap-2">
                        <Checkbox
                          checked={selectedAttachments.includes(attachment.id)}
                          onCheckedChange={() => toggleAttachment(attachment.id)}
                        />
                        {getAttachmentIcon(attachment.attachmentType)}
                        <span className="text-sm">
                          {attachment.fileName || `${attachment.attachmentType}_${attachment.serialNo}`}
                        </span>
                        <Badge variant="outline" className="text-xs">
                          {attachment.currentRevision}
                        </Badge>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="p-4 text-center text-muted-foreground">
                    <p className="text-sm">첨부파일이 없습니다.</p>
                  </div>
                )}
              </div>
            </div>

            <Separator />

              {/* 추가 메시지 */}
              <div className="space-y-2">
                <Label htmlFor="message" className="text-sm font-medium">
                  추가 메시지 (선택사항)
                </Label>
                <textarea
                  id="message"
                  className="w-full min-h-[80px] p-3 text-sm border rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="업체에 전달할 추가 메시지를 입력하세요..."
                  value={additionalMessage}
                  onChange={(e) => setAdditionalMessage(e.target.value)}
                />
              </div>

              {/* PDF 생성 진행 상황 표시 */}
              {isGeneratingPdfs && (
                <Alert className="border-blue-500 bg-blue-50">
                  <div className="space-y-3">
                    <div className="flex items-center gap-2">
                      <RefreshCw className="h-4 w-4 animate-spin text-blue-600" />
                      <AlertTitle className="text-blue-800">기본계약서 생성 중</AlertTitle>
                    </div>
                    <AlertDescription>
                      <div className="space-y-2">
                        <p className="text-sm text-blue-700">{currentGeneratingContract}</p>
                        <Progress value={pdfGenerationProgress} className="h-2" />
                        <p className="text-xs text-blue-600">
                          {Math.round(pdfGenerationProgress)}% 완료
                        </p>
                      </div>
                    </AlertDescription>
                  </div>
                </Alert>
              )}
            </TabsContent>

            <TabsContent value="template" className="mt-0 space-y-6 pr-4">
              {/* 이메일 발송 설정 및 미리보기 섹션 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2 text-sm font-medium">
                    <Mail className="h-4 w-4" />
                    이메일 발송 설정
                  </div>
                  <div className="flex items-center gap-2">
                    <Checkbox
                      id="hasToSendEmail"
                      checked={hasToSendEmail}
                      onCheckedChange={setHasToSendEmail}
                    />
                    <Label htmlFor="hasToSendEmail" className="text-sm">
                      이메일 발송
                    </Label>
                  </div>
                </div>

                {/* 이메일 발송 여부에 따른 설명 */}
                <Alert className={cn(
                  "border-2",
                  hasToSendEmail ? "border-blue-200 bg-blue-50" : "border-gray-200 bg-gray-50"
                )}>
                  <Mail className={cn("h-4 w-4", hasToSendEmail ? "text-blue-600" : "text-gray-600")} />
                  <AlertTitle className={cn(hasToSendEmail ? "text-blue-800" : "text-gray-800")}>
                    {hasToSendEmail ? "이메일 발송 모드" : "RFQ만 발송 모드"}
                  </AlertTitle>
                  <AlertDescription className={cn("text-sm", hasToSendEmail ? "text-blue-700" : "text-gray-700")}>
                    {hasToSendEmail
                      ? "선택된 이메일 템플릿으로 RFQ와 함께 이메일을 발송합니다."
                      : "EVCP 시스템에서 RFQ만 발송하고 이메일은 발송하지 않습니다."
                    }
                  </AlertDescription>
                </Alert>

                {/* 이메일 발송 시에만 미리보기 표시 */}
                {hasToSendEmail && (
                  <div className="space-y-4">
                      <div className="space-y-4">
                        {/* 미리보기 새로고침 버튼 */}
                        <div className="flex justify-end">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => generateTemplatePreview(selectedTemplateSlug)}
                            disabled={isGeneratingPreview}
                          >
                            {isGeneratingPreview ? (
                              <RefreshCw className="h-4 w-4 animate-spin mr-2" />
                            ) : (
                              '미리보기 새로고침'
                            )}
                          </Button>
                        </div>

                        {/* 미리보기 */}
                        <div className="space-y-2">
                          <Label className="text-sm font-medium">이메일 미리보기</Label>
                          {isGeneratingPreview ? (
                            <div className="h-96 border rounded-lg flex items-center justify-center">
                              <div className="text-center">
                                <RefreshCw className="h-8 w-8 animate-spin mx-auto mb-2 text-blue-500" />
                                <p className="text-sm text-muted-foreground">미리보기 생성 중...</p>
                              </div>
                            </div>
                          ) : templatePreview ? (
                            <div className="space-y-4">
                              {/* 제목 미리보기 */}
                              <div className="p-3 bg-blue-50 rounded-lg">
                                <Label className="text-xs font-medium text-blue-900">제목:</Label>
                                <p className="font-semibold text-blue-900 break-words">{templatePreview.subject}</p>
                              </div>

                              {/* 본문 미리보기 */}
                              <div className="border rounded-lg bg-white">
                                <iframe
                                  srcDoc={templatePreview.content}
                                  sandbox="allow-same-origin"
                                  className="w-full h-96 border-0 rounded-lg"
                                  title="Template Preview"
                                />
                              </div>
                            </div>
                          ) : (
                            <div className="h-96 border rounded-lg flex items-center justify-center">
                              <div className="text-center">
                                <Mail className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                                <p className="text-gray-500 mb-2">미리보기를 생성하면 이메일 내용이 표시됩니다</p>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => generateTemplatePreview(selectedTemplateSlug)}
                                >
                                  미리보기 생성
                                </Button>
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    
                  </div>
                )}

                </div>
            </TabsContent>
          </div>
        </Tabs>

        <DialogFooter className="flex-shrink-0">
          <Alert className="max-w-md">
            <div className="flex items-center gap-2">
              <AlertCircle className="h-4 w-4 flex-shrink-0" />
              <AlertDescription className="text-xs">
                발송 후에는 취소할 수 없습니다. 발송 내용을 다시 한번 확인해주세요.
              </AlertDescription>
            </div>
          </Alert>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isSending}
          >
            취소
          </Button>
          <Button
            onClick={handleSend}
            disabled={isSending || isGeneratingPdfs}
          >
            {isGeneratingPdfs ? (
              <>
                <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                RFQ 송부중... ({Math.round(pdfGenerationProgress)}%)
              </>
            ) : isSending ? (
              <>
                <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                발송중...
              </>
            ) : (
              <>
                <Send className="h-4 w-4 mr-2" />
                RFQ 발송
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>

      {/* 재발송 확인 다이얼로그 */}
      <AlertDialog open={showResendConfirmDialog} onOpenChange={setShowResendConfirmDialog}>
        <AlertDialogContent className="max-w-2xl">
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-yellow-600" />
              재발송 확인
            </AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-4">
                <p className="text-sm">
                  <span className="font-semibold text-yellow-700">{resendVendorsInfo.count}개 업체</span>가 재발송 대상입니다.
                </p>

                {/* 재발송 대상 업체 목록 및 계약서 설정 */}
                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                  <p className="text-sm font-medium text-yellow-800 mb-3">재발송 대상 업체 및 계약서 설정:</p>
                  <div className="space-y-2">
                    {vendorsWithRecipients
                      .filter(v => v.sendVersion && v.sendVersion > 0)
                      .map(vendor => {
                        const contracts = [];
                        if (vendor.ndaYn) contracts.push("NDA");
                        if (vendor.generalGtcYn) contracts.push("General GTC");
                        if (vendor.projectGtcYn) contracts.push("Project GTC");
                        if (vendor.agreementYn) contracts.push("기술자료");

                        return (
                          <div key={vendor.vendorId} className="flex items-center justify-between p-2 bg-white rounded border border-yellow-100">
                            <div className="flex items-center gap-3">
                              <span className="w-1.5 h-1.5 bg-yellow-600 rounded-full" />
                              <div>
                                <span className="text-sm font-medium text-yellow-900">{vendor.vendorName}</span>
                                {contracts.length > 0 && (
                                  <div className="text-xs text-yellow-700 mt-0.5">
                                    계약서: {contracts.join(", ")}
                                  </div>
                                )}
                              </div>
                            </div>
                            {contracts.length > 0 && (
                              <div className="flex items-center gap-2">
                                <Checkbox
                                  checked={!skipContractsForVendor[vendor.vendorId]}
                                  onCheckedChange={(checked) => {
                                    setSkipContractsForVendor(prev => ({
                                      ...prev,
                                      [vendor.vendorId]: !checked
                                    }));
                                  }}
                                // className="data-[state=checked]:bg-orange-600 data-[state=checked]:border-orange-600"
                                />
                                <span className="text-xs text-yellow-800">
                                  {skipContractsForVendor[vendor.vendorId] ? "계약서 유지" : "계약서 재생성"}
                                </span>
                              </div>
                            )}
                          </div>
                        );
                      })}
                  </div>

                  {/* 전체 선택 버튼 */}
                  {vendorsWithRecipients.some(v => v.sendVersion && v.sendVersion > 0 &&
                    (v.ndaYn || v.generalGtcYn || v.projectGtcYn || v.agreementYn)) && (
                      <div className="mt-3 pt-3 border-t border-yellow-300 flex justify-end gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            const resendVendors = vendorsWithRecipients.filter(v => v.sendVersion && v.sendVersion > 0);
                            const newSkipOptions: Record<number, boolean> = {};
                            resendVendors.forEach(v => {
                              newSkipOptions[v.vendorId] = true; // 모두 유지
                            });
                            setSkipContractsForVendor(newSkipOptions);
                          }}
                        >
                          전체 계약서 유지
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            const resendVendors = vendorsWithRecipients.filter(v => v.sendVersion && v.sendVersion > 0);
                            const newSkipOptions: Record<number, boolean> = {};
                            resendVendors.forEach(v => {
                              newSkipOptions[v.vendorId] = false; // 모두 재생성
                            });
                            setSkipContractsForVendor(newSkipOptions);
                          }}
                        >
                          전체 계약서 재생성
                        </Button>
                      </div>
                    )}
                </div>

                {/* 경고 메시지 */}
                <Alert className="border-red-200 bg-red-50">
                  <AlertCircle className="h-4 w-4 text-red-600" />
                  <AlertTitle className="text-red-800">중요 안내사항</AlertTitle>
                  <AlertDescription className="text-red-700 space-y-2">
                    <ul className="list-disc list-inside space-y-1 text-sm">
                      <li>기존에 작성된 견적 데이터가 <strong>모두 초기화</strong>됩니다.</li>
                      <li>업체는 처음부터 새로 견적서를 작성해야 합니다.</li>
                      <li>이전에 제출한 견적서는 더 이상 유효하지 않습니다.</li>
                      {Object.entries(skipContractsForVendor).some(([vendorId, skip]) => !skip &&
                        vendorsWithRecipients.find(v => v.vendorId === Number(vendorId))) && (
                          <li className="text-orange-700 font-medium">
                            ⚠️ 선택한 업체의 기존 기본계약서가 <strong>삭제</strong>되고 새로운 계약서가 발송됩니다.
                          </li>
                        )}
                      <li>이 작업은 <strong>취소할 수 없습니다</strong>.</li>
                    </ul>
                  </AlertDescription>
                </Alert>

                <p className="text-sm text-muted-foreground">
                  재발송을 진행하시겠습니까?
                </p>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => {
              setShowResendConfirmDialog(false);
              // 취소 시 옵션은 유지 (사용자가 설정한 상태 그대로)
            }}>
              취소
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                setShowResendConfirmDialog(false);
                proceedWithSend();
              }}
            >
              <RefreshCw className="h-4 w-4 mr-2" />
              재발송 진행
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Dialog>
  );
}