summaryrefslogtreecommitdiff
path: root/lib/bidding/detail/table/bidding-invitation-dialog.tsx
blob: cd79850a006c23165a7c880b7388ca889f5e9071 (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
'use client'

import * as React from 'react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Progress } from '@/components/ui/progress'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { cn } from '@/lib/utils'
import {
  Mail,
  Building2,
  Calendar,
  FileText,
  CheckCircle,
  Info,
  RefreshCw,
  Plus,
  X
} from 'lucide-react'
import { sendBiddingBasicContracts, getSelectedVendorsForBidding, getExistingBasicContractsForBidding } from '../../pre-quote/service'
import { getActiveContractTemplates } from '../../service'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'

interface VendorContractRequirement {
  vendorId: number
  vendorName: string
  vendorCode?: string
  vendorCountry?: string
  contactPerson?: string
  contactEmail?: string
  ndaYn?: boolean
  generalGtcYn?: boolean
  projectGtcYn?: boolean
  agreementYn?: boolean
  biddingCompanyId: number
  biddingId: number
}

interface BasicContractTemplate {
  id: number
  templateName: string
  revision: number
  status: string
  filePath: string | null
  validityPeriod: number | null
  legalReviewRequired: boolean
  createdAt: Date | null
}

interface SelectedContract {
  templateId: number
  templateName: string
  contractType: string
  checked: boolean
}

interface BiddingInvitationDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  vendors: VendorContractRequirement[]
  biddingId: number
  biddingTitle: string
  projectName?: string
  onSend: (data: {
    vendors: Array<{
      vendorId: number
      vendorName: string
      vendorCode?: string
      vendorCountry?: string
      selectedMainEmail: string
      additionalEmails: string[]
      contractRequirements: {
        ndaYn: boolean
        generalGtcYn: boolean
        projectGtcYn: boolean
        agreementYn: boolean
      }
      biddingCompanyId: number
      biddingId: number
      hasExistingContracts?: boolean
    }>
    generatedPdfs: Array<{
      key: string
      buffer: number[]
      fileName: string
    }>
    message?: string
  }) => Promise<void>
}

export function BiddingInvitationDialog({
  open,
  onOpenChange,
  vendors,
  biddingId,
  biddingTitle,
  projectName,
  onSend,
}: BiddingInvitationDialogProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()

  // 기본계약 관련 상태
  const [existingContracts, setExistingContracts] = React.useState<any[]>([])
  const [isGeneratingPdfs, setIsGeneratingPdfs] = React.useState(false)
  const [pdfGenerationProgress, setPdfGenerationProgress] = React.useState(0)
  const [currentGeneratingContract, setCurrentGeneratingContract] = React.useState('')

  // 기본계약서 템플릿 관련 상태
  const [availableTemplates, setAvailableTemplates] = React.useState<any[]>([])
  const [selectedContracts, setSelectedContracts] = React.useState<SelectedContract[]>([])
  const [isLoadingTemplates, setIsLoadingTemplates] = React.useState(false)
  const [additionalMessage, setAdditionalMessage] = React.useState('')

  // 선택된 업체들 (사전견적에서 선정된 업체들만)
  const selectedVendors = React.useMemo(() =>
    vendors.filter(vendor => vendor.ndaYn || vendor.generalGtcYn || vendor.projectGtcYn || vendor.agreementYn),
    [vendors]
  )

  // 기존 계약이 있는 업체들과 없는 업체들 분리
  const vendorsWithExistingContracts = React.useMemo(() =>
    selectedVendors.filter(vendor =>
      existingContracts.some((ec: any) =>
        ec.vendorId === vendor.vendorId && ec.biddingCompanyId === vendor.biddingCompanyId
      )
    ),
    [selectedVendors, existingContracts]
  )

  const vendorsWithoutExistingContracts = React.useMemo(() =>
    selectedVendors.filter(vendor =>
      !existingContracts.some((ec: any) =>
        ec.vendorId === vendor.vendorId && ec.biddingCompanyId === vendor.biddingCompanyId
      )
    ),
    [selectedVendors, existingContracts]
  )

  // 다이얼로그가 열릴 때 기존 계약 조회 및 템플릿 로드
  React.useEffect(() => {
    if (open) {
      const fetchInitialData = async () => {
        setIsLoadingTemplates(true);
        try {
          const [contractsResult, templatesData] = await Promise.all([
            getSelectedVendorsForBidding(biddingId),
            getActiveContractTemplates(),
          ]);

          // 기존 계약 조회 (사전견적에서 보낸 기본계약 확인) - 서버 액션 사용
          const existingContracts = await getExistingBasicContractsForBidding(biddingId);
          setExistingContracts(existingContracts.success ? existingContracts.contracts || [] : []);

          // 템플릿 로드 (4개 타입만 필터링)
          // 4개 템플릿 타입만 필터링: 비밀, General, Project, 기술자료
          const allowedTemplateNames = ['비밀', 'General GTC', '기술', '기술자료'];
          const rawTemplates = templatesData.templates || [];
          const filteredTemplates = rawTemplates.filter((template: any) =>
            allowedTemplateNames.some(allowedName =>
              template.templateName.includes(allowedName) ||
              allowedName.includes(template.templateName)
            )
          );
          setAvailableTemplates(filteredTemplates as any);
          const initialSelected = filteredTemplates.map((template: any) => ({
            templateId: template.id,
            templateName: template.templateName,
            contractType: template.templateName,
            checked: false
          }));
          setSelectedContracts(initialSelected);
        } catch (error) {
          console.error('초기 데이터 로드 실패:', error);
          toast({
            title: '오류',
            description: '기본 정보를 불러오는 데 실패했습니다.',
            variant: 'destructive',
          });
          setAvailableTemplates([]);
          setSelectedContracts([]);
        } finally {
          setIsLoadingTemplates(false);
        }
      }
      fetchInitialData();
    }
  }, [open, biddingId, toast]);

  const handleOpenChange = (open: boolean) => {
    onOpenChange(open)
    if (!open) {
      setSelectedContracts([])
      setAdditionalMessage('')
      setIsGeneratingPdfs(false)
      setPdfGenerationProgress(0)
      setCurrentGeneratingContract('')
    }
  }

  // 기본계약서 선택 토글
  const toggleContractSelection = (templateId: number) => {
    setSelectedContracts(prev =>
      prev.map(contract =>
        contract.templateId === templateId
          ? { ...contract, checked: !contract.checked }
          : contract
      )
    )
  }

  // 모든 기본계약서 선택/해제
  const toggleAllContractSelection = (checked: boolean | 'indeterminate') => {
    setSelectedContracts(prev =>
      prev.map(contract => ({ ...contract, checked: !!checked }))
    )
  }

  // PDF 생성 유틸리티 함수
  const generateBasicContractPdf = async (
    template: BasicContractTemplate,
    vendorId: number
  ): Promise<{ buffer: number[]; fileName: string }> => {
    try {
      // 1. 템플릿 데이터 준비 (서버 API 호출)
      const prepareResponse = await fetch("/api/contracts/prepare-template", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          templateName: template.templateName,
          vendorId,
        }),
      });
  
      if (!prepareResponse.ok) {
        throw new Error("템플릿 준비 실패");
      }
  
      const { template: preparedTemplate, templateData } = await prepareResponse.json();
  
      // 2. 템플릿 파일 다운로드
      const templateResponse = await fetch("/api/contracts/get-template", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ templatePath: preparedTemplate.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 { default: WebViewer } = await import("@pdftron/webviewer");
  
      const tempDiv = document.createElement('div');
      tempDiv.style.display = 'none';
      document.body.appendChild(tempDiv);
  
      try {
        const instance = await WebViewer(
          {
            path: "/pdftronWeb",
            licenseKey: process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY,
            fullAPI: true,
          },
          tempDiv
        );
  
        const { Core } = instance;
        const { createDocument } = Core;
  
        const templateDoc = await createDocument(templateFile, {
          filename: templateFile.name,
          extension: 'docx',
        });
  
        // 변수 치환 적용
        await templateDoc.applyTemplateValues(templateData);
  
        // PDF 변환
        const fileData = await templateDoc.getFileData();
        const pdfBuffer = await Core.officeToPDFBuffer(fileData, { extension: 'docx' });
  
        const fileName = `${template.templateName}_${Date.now()}.pdf`;
  
        return {
          buffer: Array.from(pdfBuffer), // Uint8Array를 일반 배열로 변환
          fileName
        };
  
      } finally {
        if (tempDiv.parentNode) {
          document.body.removeChild(tempDiv);
        }
      }
    } catch (error) {
      console.error(`기본계약 PDF 생성 실패 (${template.templateName}):`, error);
      throw error;
    }
  };

  const handleSendInvitation = () => {
    const selectedContractTemplates = selectedContracts.filter(c => c.checked);

    startTransition(async () => {
      try {
        let generatedPdfs: Array<{
          key: string
          buffer: number[]
          fileName: string
        }> = []

        const generatedPdfsMap = new Map<string, { buffer: number[], fileName: string }>()

        // 선택된 템플릿이 있는 경우에만 PDF 생성
        if (selectedContractTemplates.length > 0) {
          setIsGeneratingPdfs(true)
          setPdfGenerationProgress(0)

          let generatedCount = 0;
          for (const vendor of selectedVendors) {
            // 사전견적에서 이미 기본계약을 보낸 벤더인지 확인
            const hasExistingContract = existingContracts.some((ec: any) =>
              ec.vendorId === vendor.vendorId && ec.biddingCompanyId === vendor.biddingCompanyId
            );

            if (hasExistingContract) {
              console.log(`벤더 ${vendor.vendorName}는 사전견적에서 이미 기본계약을 받았으므로 건너뜁니다.`);
              generatedCount++;
              setPdfGenerationProgress((generatedCount / selectedVendors.length) * 100);
              continue;
            }

          for (const contract of selectedContractTemplates) {
            setCurrentGeneratingContract(`${vendor.vendorName} - ${contract.templateName}`);
            const templateDetails = availableTemplates.find(t => t.id === contract.templateId);

            if (templateDetails) {
              const pdfData = await generateBasicContractPdf(templateDetails, vendor.vendorId);
              // sendBiddingBasicContracts와 동일한 키 형식 사용
              let contractType = '';
              if (contract.templateName.includes('비밀')) {
                contractType = 'NDA';
              } else if (contract.templateName.includes('General GTC')) {
                contractType = 'General_GTC';
              } else if (contract.templateName.includes('기술') && !contract.templateName.includes('기술자료')) {
                contractType = 'Project_GTC';
              } else if (contract.templateName.includes('기술자료')) {
                contractType = '기술자료';
              }
              const key = `${vendor.vendorId}_${contractType}_${contract.templateName}`;
              generatedPdfsMap.set(key, pdfData);
            }
          }
          generatedCount++;
          setPdfGenerationProgress((generatedCount / selectedVendors.length) * 100);
        }

          setIsGeneratingPdfs(false);

          const pdfsArray = Array.from(generatedPdfsMap.entries()).map(([key, data]) => ({
            key,
            buffer: data.buffer,
            fileName: data.fileName,
          }));

          generatedPdfs = pdfsArray;
        }

        const vendorData = selectedVendors.map(vendor => {
          const hasExistingContract = existingContracts.some((ec: any) =>
            ec.vendorId === vendor.vendorId && ec.biddingCompanyId === vendor.biddingCompanyId
          );

          return {
            vendorId: vendor.vendorId,
            vendorName: vendor.vendorName,
            vendorCode: vendor.vendorCode,
            vendorCountry: vendor.vendorCountry,
            selectedMainEmail: vendor.contactEmail || '',
            additionalEmails: [],
            contractRequirements: {
              ndaYn: vendor.ndaYn || false,
              generalGtcYn: vendor.generalGtcYn || false,
              projectGtcYn: vendor.projectGtcYn || false,
              agreementYn: vendor.agreementYn || false
            },
            biddingCompanyId: vendor.biddingCompanyId,
            biddingId: vendor.biddingId,
            hasExistingContracts: hasExistingContract
          };
        });

        await onSend({
          vendors: vendorData,
          generatedPdfs: generatedPdfs,
          message: additionalMessage
        });

      } catch (error) {
        console.error('본입찰 초대 실패:', error);
        toast({
          title: '오류',
          description: '본입찰 초대 중 오류가 발생했습니다.',
          variant: 'destructive',
        });
        setIsGeneratingPdfs(false);
      }
    })
  }

  const selectedContractCount = selectedContracts.filter(c => c.checked).length;

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-[800px] max-h-[90vh] flex flex-col"  style={{width:900, maxWidth:900}}>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Mail className="w-5 h-5" />
            본입찰 초대
          </DialogTitle>
          <DialogDescription>
            {biddingTitle} - 선정된 {selectedVendors.length}개 업체에 본입찰 초대와 기본계약서를 발송합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto px-1" style={{ maxHeight: 'calc(70vh - 200px)' }}>
          <div className="space-y-6 pr-4">
            {/* 기존 계약 정보 */}
            {vendorsWithExistingContracts.length > 0 && (
              <Alert className="border-orange-500 bg-orange-50">
                <Info className="h-4 w-4 text-orange-600" />
                <AlertTitle className="text-orange-800">기존 계약 정보</AlertTitle>
                <AlertDescription className="text-orange-700">
                  사전견적에서 이미 기본계약을 받은 업체가 있습니다.
                  해당 업체들은 계약서 재생성을 건너뜁니다. (본입찰 초대는 정상 진행됩니다)
                </AlertDescription>
              </Alert>
            )}

            {/* 대상 업체 정보 */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-base">
                  <Building2 className="h-5 w-5 text-green-600" />
                  초대 대상 업체 ({selectedVendors.length}개)
                </CardTitle>
              </CardHeader>
              <CardContent>
                {selectedVendors.length === 0 ? (
                  <div className="text-center py-6 text-muted-foreground">
                    초대 가능한 업체가 없습니다.
                  </div>
                ) : (
                  <div className="space-y-4">
                    {/* 계약서가 생성될 업체들 */}
                    {vendorsWithoutExistingContracts.length > 0 && (
                      <div>
                        <h4 className="text-sm font-medium text-green-700 mb-2 flex items-center gap-2">
                          <CheckCircle className="h-4 w-4 text-green-600" />
                          계약서 생성 대상 ({vendorsWithoutExistingContracts.length}개)
                        </h4>
                        <div className="space-y-2 max-h-32 overflow-y-auto">
                          {vendorsWithoutExistingContracts.map((vendor) => (
                            <div key={vendor.vendorId} className="flex items-center gap-2 text-sm p-2 bg-green-50 rounded border border-green-200">
                              <CheckCircle className="h-4 w-4 text-green-600" />
                              <span className="font-medium">{vendor.vendorName}</span>
                              <Badge variant="outline" className="text-xs">
                                {vendor.vendorCode}
                              </Badge>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* 기존 계약이 있는 업체들 */}
                    {vendorsWithExistingContracts.length > 0 && (
                      <div>
                        <h4 className="text-sm font-medium text-orange-700 mb-2 flex items-center gap-2">
                          <X className="h-4 w-4 text-orange-600" />
                          기존 계약 존재 (계약서 재생성 건너뜀) ({vendorsWithExistingContracts.length}개)
                        </h4>
                        <div className="space-y-2 max-h-32 overflow-y-auto">
                          {vendorsWithExistingContracts.map((vendor) => (
                            <div key={vendor.vendorId} className="flex items-center gap-2 text-sm p-2 bg-orange-50 rounded border border-orange-200">
                              <X className="h-4 w-4 text-orange-600" />
                              <span className="font-medium">{vendor.vendorName}</span>
                              <Badge variant="outline" className="text-xs">
                                {vendor.vendorCode}
                              </Badge>
                              <Badge variant="secondary" className="text-xs bg-orange-100 text-orange-800">
                                계약 존재 (재생성 건너뜀)
                              </Badge>
                              <Badge variant="outline" className="text-xs border-green-500 text-green-700">
                                본입찰 초대
                              </Badge>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 기본계약서 선택 */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-base">
                  <FileText className="h-5 w-5 text-blue-600" />
                  기본계약 선택 (선택사항)
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* 템플릿 로딩 */}
                {isLoadingTemplates ? (
                  <div className="text-center py-6">
                    <RefreshCw className="h-6 w-6 animate-spin mx-auto mb-2 text-blue-600" />
                    <p className="text-sm text-muted-foreground">기본계약서 템플릿을 불러오는 중...</p>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {availableTemplates.length === 0 ? (
                      <div className="text-center py-8 text-muted-foreground">
                        <FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                        <p>사용 가능한 기본계약서 템플릿이 없습니다.</p>
                      </div>
                    ) : (
                      <>
                        <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                          <div className="flex items-center gap-2">
                            <Checkbox
                              id="select-all-contracts"
                              checked={selectedContracts.length > 0 && selectedContracts.every(c => c.checked)}
                              onCheckedChange={toggleAllContractSelection}
                            />
                            <Label htmlFor="select-all-contracts" className="font-medium">
                              전체 선택 ({availableTemplates.length}개 템플릿)
                            </Label>
                          </div>
                          <Badge variant="outline">
                            {selectedContractCount}개 선택됨
                          </Badge>
                        </div>
                        <div className="grid gap-3 max-h-60 overflow-y-auto">
                          {selectedContracts.map((contract) => (
                            <div
                              key={contract.templateId}
                              className={cn(
                                "flex items-center justify-between p-3 border rounded-lg hover:bg-muted/50 transition-colors cursor-pointer",
                                contract.checked && "border-blue-500 bg-blue-50"
                              )}
                              onClick={() => toggleContractSelection(contract.templateId)}
                            >
                              <div className="flex items-center gap-3">
                                <Checkbox
                                  id={`contract-${contract.templateId}`}
                                  checked={contract.checked}
                                  onCheckedChange={() => toggleContractSelection(contract.templateId)}
                                />
                                <div className="flex-1">
                                  <Label
                                    htmlFor={`contract-${contract.templateId}`}
                                    className="font-medium cursor-pointer"
                                  >
                                    {contract.templateName}
                                  </Label>
                                  <p className="text-xs text-muted-foreground mt-1">
                                    {contract.contractType}
                                  </p>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </>
                    )}

                    {/* 선택된 템플릿 요약 */}
                    {selectedContractCount > 0 && (
                      <div className="mt-4 p-3 bg-green-50 border border-green-200 rounded-lg">
                        <div className="flex items-center gap-2 mb-2">
                          <CheckCircle className="h-4 w-4 text-green-600" />
                          <span className="font-medium text-green-900 text-sm">
                            선택된 기본계약서 ({selectedContractCount}개)
                          </span>
                        </div>
                        <ul className="space-y-1 text-xs text-green-800 list-disc list-inside">
                          {selectedContracts.filter(c => c.checked).map((contract) => (
                            <li key={contract.templateId}>
                              {contract.templateName}
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 추가 메시지 */}
            <div className="space-y-2">
              <Label htmlFor="invitationMessage" className="text-sm font-medium">
                초대 메시지 (선택사항)
              </Label>
              <textarea
                id="invitationMessage"
                className="w-full min-h-[60px] 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>
            )}
          </div>
        </div>

        <DialogFooter className="flex-col sm:flex-row-reverse sm:justify-between items-center px-4 pt-4">
          <div className="flex gap-2 w-full sm:w-auto">
            <Button variant="outline" onClick={() => handleOpenChange(false)} className="w-full sm:w-auto">
              취소
            </Button>
            <Button
              onClick={handleSendInvitation}
              disabled={isPending || selectedVendors.length === 0 || isGeneratingPdfs}
              className="w-full sm:w-auto"
            >
              {isGeneratingPdfs ? (
                <>
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                  입찰 초대중... ({Math.round(pdfGenerationProgress)}%)
                </>
              ) : isPending ? (
                <>
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                  발송 중...
                </>
              ) : (
                <>
                  <Mail className="w-4 h-4 mr-2" />
                  본입찰 초대 발송
                </>
              )}
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}