summaryrefslogtreecommitdiff
path: root/lib/rfq-last/vendor/send-rfq-dialog.tsx
blob: 42470ecc48c42ffc49adcb10cb653f1f4d230297 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
"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) {
        throw new Error("서버 응답이 없습니다.");
      }

      if (!sendResult.success) {
        throw new Error(sendResult.message || "RFQ 발송에 실패했습니다.");
      }

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

    } catch (error) {
      console.error("RFQ 발송 실패:", error);
      toast.error(error instanceof Error ? error.message : "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>
  );
}