summaryrefslogtreecommitdiff
path: root/lib/basic-contract/vendor-table/basic-contract-sign-dialog.tsx
blob: 319ae4b99ebd21990e52650a586fab8963e8d454 (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
"use client";

import * as React from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { formatDate } from "@/lib/utils";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import type { WebViewerInstance } from "@pdftron/webviewer";
import type { BasicContractView } from "@/db/schema";
import {
  Upload,
  FileSignature,
  CheckCircle2,
  Search,
  Clock,
  FileText,
  User,
  AlertCircle,
  Calendar,
  Loader2,
  ArrowRight,
  Trophy,
  Target
} from "lucide-react";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { useRouter } from "next/navigation"
import { BasicContractSignViewer } from "../viewer/basic-contract-sign-viewer";
import { getVendorAttachments } from "../service";

// 계약서 상태 타입 정의
interface ContractStatus {
  id: number;
  status: 'pending' | 'completed' | 'error';
  errorMessage?: string;
}

interface BasicContractSignDialogProps {
  contracts: BasicContractView[];
  onSuccess?: () => void;
  hasSelectedRows?: boolean;
  t: (key: string) => string;
}

export function BasicContractSignDialog({ 
  contracts, 
  onSuccess, 
  hasSelectedRows = false,
  t 
}: BasicContractSignDialogProps) {
  const [open, setOpen] = React.useState(false);
  const [selectedContract, setSelectedContract] = React.useState<BasicContractView | null>(null);
  const [instance, setInstance] = React.useState<null | WebViewerInstance>(null);
  const [searchTerm, setSearchTerm] = React.useState("");
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  
  // 추가된 state들
  const [additionalFiles, setAdditionalFiles] = React.useState<any[]>([]);
  const [isLoadingAttachments, setIsLoadingAttachments] = React.useState(false);
  
  // 계약서 상태 관리
  const [contractStatuses, setContractStatuses] = React.useState<ContractStatus[]>([]);
  
  // 🔥 새로 추가: 서명/설문 완료 상태 관리
  const [surveyCompletionStatus, setSurveyCompletionStatus] = React.useState<Record<number, boolean>>({});
  const [signatureStatus, setSignatureStatus] = React.useState<Record<number, boolean>>({});
  
  const router = useRouter()

  console.log(selectedContract,"selectedContract")
  console.log(additionalFiles,"additionalFiles")
  
  // 버튼 비활성화 조건
  const isButtonDisabled = !hasSelectedRows || contracts.length === 0;

  // 비활성화 이유 텍스트
  const getDisabledReason = () => {
    if (!hasSelectedRows) {
      return t("basicContracts.toolbar.selectRows");
    }
    if (contracts.length === 0) {
      return t("basicContracts.toolbar.noPendingContracts");
    }
    return "";
  };

  // 🔥 현재 선택된 계약서의 서명 완료 가능 여부 확인
  const canCompleteCurrentContract = React.useMemo(() => {
    if (!selectedContract) return false;
    
    const contractId = selectedContract.id;
    const isComplianceTemplate = selectedContract.templateName?.includes('준법');
    
    // 1. 준법 템플릿인 경우 설문조사 완료 여부 확인
    const surveyCompleted = isComplianceTemplate ? surveyCompletionStatus[contractId] === true : true;
    
    // 2. 서명 완료 여부 확인
    const signatureCompleted = signatureStatus[contractId] === true;
    
    console.log('🔍 서명 완료 가능 여부 체크:', {
      contractId,
      isComplianceTemplate,
      surveyCompleted,
      signatureCompleted,
      canComplete: surveyCompleted && signatureCompleted
    });
    
    return surveyCompleted && signatureCompleted;
  }, [selectedContract, surveyCompletionStatus, signatureStatus]);

  // 계약서별 상태 초기화
  React.useEffect(() => {
    if (contracts.length > 0 && contractStatuses.length === 0) {
      setContractStatuses(
        contracts.map(contract => ({
          id: contract.id,
          status: 'pending' as const
        }))
      );
    }
  }, [contracts, contractStatuses.length]);

  // 완료된 계약서 수 계산
  const completedCount = contractStatuses.filter(status => status.status === 'completed').length;
  const totalCount = contracts.length;
  const allCompleted = completedCount === totalCount && totalCount > 0;

  // 현재 선택된 계약서의 상태
  const currentContractStatus = selectedContract 
    ? contractStatuses.find(status => status.id === selectedContract.id)
    : null;

  // 다음 미완료 계약서 찾기
  const getNextPendingContract = () => {
    const pendingStatuses = contractStatuses.filter(status => status.status === 'pending');
    if (pendingStatuses.length === 0) return null;
    
    const nextPendingId = pendingStatuses[0].id;
    return contracts.find(contract => contract.id === nextPendingId) || null;
  };

  // 다이얼로그 열기/닫기 핸들러
  const handleOpenChange = (isOpen: boolean) => {
    if (!isOpen && !allCompleted && completedCount > 0) {
      // 완료되지 않은 계약서가 있으면 확인 대화상자
      const confirmClose = window.confirm(
        `${completedCount}/${totalCount}개 계약서가 완료되었습니다. 정말 나가시겠습니까?`
      );
      if (!confirmClose) return;
    }
    
    setOpen(isOpen);
    
    if (!isOpen) {
      // 다이얼로그 닫을 때 상태 초기화
      setSelectedContract(null);
      setSearchTerm("");
      setAdditionalFiles([]);
      setContractStatuses([]);
      setSurveyCompletionStatus({}); // 🔥 추가
      setSignatureStatus({}); // 🔥 추가
      // WebViewer 인스턴스 정리
      if (instance) {
        try {
          instance.UI.dispose();
        } catch (error) {
          console.log("WebViewer dispose error:", error);
        }
        setInstance(null);
      }
    }
  };

  // 계약서 선택 핸들러
  const handleSelectContract = (contract: BasicContractView) => {
    console.log("계약서 선택:", contract.id, contract.templateName);
    setSelectedContract(contract);
  };

  // 검색된 계약서 필터링
  const filteredContracts = React.useMemo(() => {
    if (!searchTerm.trim()) return contracts;

    const term = searchTerm.toLowerCase();
    return contracts.filter(contract =>
      (contract.templateName || '').toLowerCase().includes(term) ||
      (contract.requestedByName || '').toLowerCase().includes(term)
    );
  }, [contracts, searchTerm]);

  // 다이얼로그가 열릴 때 첫 번째 미완료 계약서 자동 선택
  React.useEffect(() => {
    if (open && contracts.length > 0 && !selectedContract) {
      const firstPending = getNextPendingContract();
      if (firstPending) {
        setSelectedContract(firstPending);
      } else {
        setSelectedContract(contracts[0]);
      }
    }
  }, [open, contracts, selectedContract, contractStatuses]);

  // 추가 파일 가져오기 useEffect
  React.useEffect(() => {
    const fetchAdditionalFiles = async () => {
      if (!selectedContract) {
        setAdditionalFiles([]);
        return;
      }

      // "비밀유지 계약서"인 경우에만 추가 파일 가져오기
      if (selectedContract.templateName === "비밀유지 계약서") {
        setIsLoadingAttachments(true);
        try {
          const result = await getVendorAttachments(selectedContract.vendorId);
          if (result.success) {
            setAdditionalFiles(result.data);
            console.log("추가 파일 로드됨:", result.data);
          } else {
            console.error("Failed to fetch attachments:", result.error);
            setAdditionalFiles([]);
          }
        } catch (error) {
          console.error("Error fetching attachments:", error);
          setAdditionalFiles([]);
        } finally {
          setIsLoadingAttachments(false);
        }
      } else {
        setAdditionalFiles([]);
      }
    };

    fetchAdditionalFiles();
  }, [selectedContract]);

  // 🔥 설문조사 완료 콜백 함수
  const handleSurveyComplete = React.useCallback((contractId: number) => {
    console.log(`📋 설문조사 완료: 계약서 ${contractId}`);
    setSurveyCompletionStatus(prev => ({
      ...prev,
      [contractId]: true
    }));
  }, []);

  // 🔥 서명 완료 콜백 함수
  const handleSignatureComplete = React.useCallback((contractId: number) => {
    console.log(`✍️ 서명 완료: 계약서 ${contractId}`);
    setSignatureStatus(prev => ({
      ...prev,
      [contractId]: true
    }));
  }, []);

  // 서명 완료 핸들러 (수정됨)
  const completeSign = async () => {
    if (!instance || !selectedContract) return;

    // 🔥 서명 완료 가능 여부 재확인
    if (!canCompleteCurrentContract) {
      const contractId = selectedContract.id;
      const isComplianceTemplate = selectedContract.templateName?.includes('준법');
      const surveyCompleted = isComplianceTemplate ? surveyCompletionStatus[contractId] === true : true;
      const signatureCompleted = signatureStatus[contractId] === true;
      
      if (!surveyCompleted) {
        toast.error("준법 설문조사를 먼저 완료해주세요.", {
          description: "설문조사 탭에서 모든 필수 항목을 완료해주세요.",
          icon: <AlertCircle className="h-5 w-5 text-red-500" />
        });
        return;
      }
      
      if (!signatureCompleted) {
        toast.error("계약서에 서명을 먼저 완료해주세요.", {
          description: "문서의 서명 필드에 서명해주세요.",
          icon: <Target className="h-5 w-5 text-blue-500" />
        });
        return;
      }
      
      return;
    }

    setIsSubmitting(true);
    try {
      const { documentViewer, annotationManager } = instance.Core;
      const doc = documentViewer.getDocument();
      const xfdfString = await annotationManager.exportAnnotations();

      // 폼 필드 데이터 수집
      const fieldManager = annotationManager.getFieldManager();
      const fields = fieldManager.getFields();
      const formData: any = {};
      fields.forEach((field: any) => {
        formData[field.name] = field.value;
      });

      const data = await doc.getFileData({
        xfdfString,
        downloadType: "pdf",
      });
      
      // FormData 생성 및 파일 추가
      const submitFormData = new FormData();
      submitFormData.append('file', new Blob([data], { type: 'application/pdf' }));
      submitFormData.append('tableRowId', selectedContract.id.toString());
      submitFormData.append('templateName', selectedContract.signedFileName || '');
      
      // 폼 필드 데이터 추가
      if (Object.keys(formData).length > 0) {
        submitFormData.append('formData', JSON.stringify(formData));
      }
      
      // API 호출
      const response = await fetch('/api/upload/signed-contract', {
        method: 'POST',
        body: submitFormData,
        next: { tags: ["basicContractView-vendor"] },
      });
      
      const result = await response.json();

      if (result.result) {
        // 성공시 해당 계약서 상태를 완료로 업데이트
        setContractStatuses(prev => 
          prev.map(status => 
            status.id === selectedContract.id 
              ? { ...status, status: 'completed' as const }
              : status
          )
        );

        toast.success("계약서 서명이 완료되었습니다!", {
          description: `${selectedContract.templateName} - ${completedCount + 1}/${totalCount}개 완료`,
          icon: <CheckCircle2 className="h-5 w-5 text-green-500" />
        });

        // 다음 미완료 계약서로 자동 이동
        const nextContract = getNextPendingContract();
        if (nextContract) {
          setSelectedContract(nextContract);
          toast.info(`다음 계약서로 이동합니다`, {
            description: nextContract.templateName,
            icon: <ArrowRight className="h-4 w-4 text-blue-500" />
          });
        } else {
          // 모든 계약서 완료시
          toast.success("🎉 모든 계약서 서명이 완료되었습니다!", {
            description: `총 ${totalCount}개 계약서 서명 완료`,
            icon: <Trophy className="h-5 w-5 text-yellow-500" />
          });
        }

        router.refresh();
      } else {
        // 실패시 에러 상태 업데이트
        setContractStatuses(prev => 
          prev.map(status => 
            status.id === selectedContract.id 
              ? { ...status, status: 'error' as const, errorMessage: result.error }
              : status
          )
        );

        toast.error("서명 처리 중 오류가 발생했습니다", {
          description: result.error,
          icon: <AlertCircle className="h-5 w-5 text-red-500" />
        });
      }
    } catch (error) {
      console.error("서명 완료 중 오류:", error);
      
      // 에러 상태 업데이트
      setContractStatuses(prev => 
        prev.map(status => 
          status.id === selectedContract.id 
            ? { ...status, status: 'error' as const, errorMessage: '서명 처리 중 오류가 발생했습니다' }
            : status
        )
      );

      toast.error("서명 처리 중 오류가 발생했습니다");
    } finally {
      setIsSubmitting(false);
    }
  };

  // 모든 서명 완료 핸들러
  const completeAllSigns = () => {
    setOpen(false);
    if (onSuccess) {
      onSuccess();
    }
    toast.success("모든 계약서 서명이 완료되었습니다!", {
      description: "계약서 관리 페이지가 새로고침됩니다.",
      icon: <Trophy className="h-5 w-5 text-yellow-500" />
    });
  };

  return (
    <>
      {/* 서명 버튼 */}
      <Button
        variant="outline"
        size="sm"
        onClick={() => setOpen(true)}
        disabled={isButtonDisabled}
        className="gap-2 transition-all hover:bg-blue-50 hover:text-blue-600 hover:border-blue-200 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <Upload 
          className={`size-4 ${isButtonDisabled ? 'text-gray-400' : 'text-blue-500'}`} 
          aria-hidden="true" 
        />
        <span className="hidden sm:inline flex items-center">
          {t("basicContracts.toolbar.sign")}
          {contracts.length > 0 && !isButtonDisabled && (
            <Badge variant="secondary" className="ml-2 bg-blue-100 text-blue-700 hover:bg-blue-200">
              {contracts.length}
            </Badge>
          )}
          {isButtonDisabled && (
            <span className="ml-2 text-xs text-gray-400">
              ({getDisabledReason()})
            </span>
          )}
        </span>
      </Button>

      {/* 서명 다이얼로그 */}
      <Dialog open={open} onOpenChange={handleOpenChange}>
        <DialogContent className="max-w-7xl w-[95vw] h-[90vh] p-0 flex flex-col overflow-hidden" style={{width:'95vw', maxWidth:'95vw'}}>
          {/* 고정 헤더 - 진행 상황 표시 */}
          <DialogHeader className="px-6 py-4 bg-gradient-to-r from-blue-50 to-purple-50 border-b flex-shrink-0">
            <DialogTitle className="text-xl font-bold flex items-center justify-between text-gray-800">
              <div className="flex items-center">
                <FileSignature className="mr-2 h-5 w-5 text-blue-500" />
                {t("basicContracts.dialog.title")}
                {/* 진행 상황 표시 */}
                <Badge variant="outline" className="ml-3 bg-blue-50 text-blue-700 border-blue-200">
                  {completedCount}/{totalCount} 완료
                </Badge>
                {/* 추가 파일 로딩 표시 */}
                {isLoadingAttachments && (
                  <Loader2 className="ml-2 h-4 w-4 animate-spin text-blue-500" />
                )}
              </div>
              
              {allCompleted && (
                <Badge variant="default" className="bg-green-100 text-green-700 border-green-200">
                  <Trophy className="h-4 w-4 mr-1" />
                  전체 완료!
                </Badge>
              )}
            </DialogTitle>

            {/* 진행률 바 */}
            {totalCount > 1 && (
              <div className="mt-3">
                <div className="flex justify-between text-xs text-gray-600 mb-1">
                  <span>전체 진행률</span>
                  <span>{Math.round((completedCount / totalCount) * 100)}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-gradient-to-r from-blue-500 to-green-500 h-2 rounded-full transition-all duration-500"
                    style={{ width: `${(completedCount / totalCount) * 100}%` }}
                  />
                </div>
              </div>
            )}
          </DialogHeader>

          {/* 메인 컨텐츠 영역 - Flexbox 사용 */}
          <div className="flex flex-1 min-h-0 overflow-hidden">
            {/* 왼쪽 영역 - 계약서 목록 (고정 너비) */}
            <div className="w-80 border-r border-gray-200 bg-gray-50 flex flex-col flex-shrink-0">
              <div className="p-3 border-b flex-shrink-0">
                <div className="relative">
                  <div className="absolute inset-y-0 left-2 flex items-center pointer-events-none">
                    <Search className="h-4 w-4 text-gray-400" />
                  </div>
                  <Input
                    placeholder={t("basicContracts.dialog.searchPlaceholder")}
                    className="bg-white pl-8 text-sm"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                </div>
              </div>

              <ScrollArea className="flex-1">
                <div className="p-2">
                  {filteredContracts.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-32 text-center">
                      <FileText className="h-8 w-8 text-gray-300 mb-2" />
                      <p className="text-gray-500 text-sm font-medium">{t("basicContracts.dialog.noDocuments")}</p>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      {filteredContracts.map((contract) => {
                        const contractStatus = contractStatuses.find(status => status.id === contract.id);
                        const isCompleted = contractStatus?.status === 'completed';
                        const hasError = contractStatus?.status === 'error';
                        
                        // 🔥 계약서별 완료 상태 확인
                        const isComplianceTemplate = contract.templateName?.includes('준법');
                        const hasSurveyCompleted = isComplianceTemplate ? surveyCompletionStatus[contract.id] === true : true;
                        const hasSignatureCompleted = signatureStatus[contract.id] === true;
                        
                        return (
                          <Button
                            key={contract.id}
                            variant="outline"
                            className={cn(
                              "w-full justify-start text-left h-auto p-2 bg-white transition-colors",
                              "border border-gray-200 rounded-md",
                              selectedContract?.id === contract.id && !isCompleted && "border-blue-500 bg-blue-50 shadow-sm",
                              isCompleted && "border-green-200 bg-green-50",
                              hasError && "border-red-200 bg-red-50",
                              !isCompleted && !hasError && "hover:bg-blue-50 hover:border-blue-200"
                            )}
                            onClick={() => handleSelectContract(contract)}
                            disabled={isCompleted}
                          >
                            <div className="flex flex-col w-full space-y-1">
                              {/* 첫 번째 줄: 제목 + 상태 */}
                              <div className="flex items-center justify-between w-full">
                                <span className="font-medium text-xs truncate text-gray-800 flex items-center min-w-0">
                                  <FileText className="h-3 w-3 mr-1 text-blue-500 flex-shrink-0" />
                                  <span className="truncate">{contract.templateName || t("basicContracts.dialog.document")}</span>
                                  {/* 비밀유지 계약서인 경우 표시 */}
                                  {contract.templateName === "비밀유지 계약서" && (
                                    <Badge variant="outline" className="ml-1 bg-green-50 text-green-700 border-green-200 text-xs">
                                      NDA
                                    </Badge>
                                  )}
                                </span>
                                
                                {/* 상태 표시 */}
                                {isCompleted ? (
                                  <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200 text-xs ml-2 flex-shrink-0">
                                    <CheckCircle2 className="h-3 w-3 mr-1" />
                                    완료
                                  </Badge>
                                ) : hasError ? (
                                  <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200 text-xs ml-2 flex-shrink-0">
                                    <AlertCircle className="h-3 w-3 mr-1" />
                                    오류
                                  </Badge>
                                ) : (
                                  <Badge variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-200 text-xs ml-2 flex-shrink-0">
                                    대기
                                  </Badge>
                                )}
                              </div>
                              
                              {/* 🔥 완료 상태 표시 */}
                              {!isCompleted && !hasError && (
                                <div className="flex items-center space-x-2 text-xs">
                                  {isComplianceTemplate && (
                                    <span className={`flex items-center ${hasSurveyCompleted ? 'text-green-600' : 'text-gray-400'}`}>
                                      <CheckCircle2 className={`h-3 w-3 mr-1 ${hasSurveyCompleted ? 'text-green-500' : 'text-gray-300'}`} />
                                      설문
                                    </span>
                                  )}
                                  <span className={`flex items-center ${hasSignatureCompleted ? 'text-green-600' : 'text-gray-400'}`}>
                                    <Target className={`h-3 w-3 mr-1 ${hasSignatureCompleted ? 'text-green-500' : 'text-gray-300'}`} />
                                    서명
                                  </span>
                                </div>
                              )}
                              
                              {/* 두 번째 줄: 사용자 + 날짜 */}
                              <div className="flex items-center justify-between text-xs text-gray-500">
                                <div className="flex items-center min-w-0">
                                  <User className="h-3 w-3 mr-1 flex-shrink-0" />
                                  <span className="truncate">{contract.requestedByName || t("basicContracts.dialog.unknown")}</span>
                                </div>
                                <div className="flex items-center ml-2 flex-shrink-0">
                                  <Calendar className="h-3 w-3 mr-1 flex-shrink-0" />
                                  <span>{formatDate(contract.createdAt)}</span>
                                </div>
                              </div>

                              {/* 에러 메시지 표시 */}
                              {hasError && contractStatus?.errorMessage && (
                                <div className="text-xs text-red-600 mt-1">
                                  {contractStatus.errorMessage}
                                </div>
                              )}
                            </div>
                          </Button>
                        );
                      })}
                    </div>
                  )}
                </div>
              </ScrollArea>
            </div>

            {/* 오른쪽 영역 - 문서 뷰어 (확장 가능) */}
            <div className="flex-1 bg-white flex flex-col min-w-0">
              {selectedContract ? (
                <>
                  {/* 뷰어 헤더 */}
                  <div className="p-4 border-b bg-gray-50 flex-shrink-0">
                    <h3 className="font-semibold text-gray-800 flex items-center">
                      <FileText className="h-4 w-4 mr-2 text-blue-500" />
                      {selectedContract.templateName || t("basicContracts.dialog.document")}
                      
                      {/* 현재 계약서 상태 표시 */}
                      {currentContractStatus?.status === 'completed' ? (
                        <Badge variant="outline" className="ml-2 bg-green-50 text-green-700 border-green-200">
                          <CheckCircle2 className="h-3 w-3 mr-1" />
                          서명 완료
                        </Badge>
                      ) : currentContractStatus?.status === 'error' ? (
                        <Badge variant="outline" className="ml-2 bg-red-50 text-red-700 border-red-200">
                          <AlertCircle className="h-3 w-3 mr-1" />
                          처리 실패
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="ml-2 bg-yellow-50 text-yellow-700 border-yellow-200">
                          서명 대기
                        </Badge>
                      )}

                      {/* 준법 템플릿 표시 */}
                      {selectedContract.templateName?.includes('준법') && (
                        <Badge variant="outline" className="ml-2 bg-amber-50 text-amber-700 border-amber-200">
                          준법 서류
                        </Badge>
                      )}
                      
                      {/* 비밀유지 계약서인 경우 추가 파일 수 표시 */}
                      {selectedContract.templateName === "비밀유지 계약서" && additionalFiles.length > 0 && (
                        <Badge variant="outline" className="ml-2 bg-blue-50 text-blue-700 border-blue-200">
                          첨부파일 {additionalFiles.length}개
                        </Badge>
                      )}
                    </h3>
                    <div className="flex justify-between items-center mt-2 text-sm text-gray-500">
                      <span className="flex items-center">
                        <User className="h-3 w-3 mr-1" />
                        {t("basicContracts.dialog.requester")}: {selectedContract.requestedByName || t("basicContracts.dialog.unknown")}
                      </span>
                      <span className="flex items-center">
                        <Clock className="h-3 w-3 mr-1" />
                        {formatDate(selectedContract.createdAt)}
                      </span>
                    </div>
                  </div>
                  
                  {/* 뷰어 영역 - 남은 공간 모두 사용 */}
                  <div className="flex-1 min-h-0 overflow-hidden">
                    <BasicContractSignViewer
                      key={selectedContract.id}
                      contractId={selectedContract.id}
                      filePath={selectedContract.signedFilePath || undefined}
                      templateName={selectedContract.templateName || ""}
                      additionalFiles={additionalFiles}
                      instance={instance}
                      setInstance={setInstance}
                      onSurveyComplete={() => handleSurveyComplete(selectedContract.id)} // 🔥 추가
                      onSignatureComplete={() => handleSignatureComplete(selectedContract.id)} // 🔥 추가
                      t={t}
                    />
                  </div>

                  {/* 고정 푸터 - 동적 버튼 */}
                  <div className="p-4 flex justify-between items-center bg-gray-50 border-t flex-shrink-0">
                    <div className="flex items-center space-x-4">
                      {/* 현재 계약서가 완료된 경우 */}
                      {currentContractStatus?.status === 'completed' ? (
                        <p className="text-sm text-green-600 flex items-center">
                          <CheckCircle2 className="h-4 w-4 text-green-500 mr-1" />
                          이 계약서는 이미 서명이 완료되었습니다
                        </p>
                      ) : currentContractStatus?.status === 'error' ? (
                        <p className="text-sm text-red-600 flex items-center">
                          <AlertCircle className="h-4 w-4 text-red-500 mr-1" />
                          서명 처리 중 오류가 발생했습니다. 다시 시도해주세요.
                        </p>
                      ) : (
                        <>
                          {/* 🔥 완료 조건 안내 메시지 개선 */}
                          <div className="flex flex-col space-y-1">
                            <p className="text-sm text-gray-600 flex items-center">
                              <AlertCircle className="h-4 w-4 text-yellow-500 mr-1" />
                              {t("basicContracts.dialog.signWarning")}
                            </p>
                            
                            {/* 완료 상태 체크리스트 */}
                            <div className="flex items-center space-x-4 text-xs">
                              {selectedContract.templateName?.includes('준법') && (
                                <span className={`flex items-center ${surveyCompletionStatus[selectedContract.id] ? 'text-green-600' : 'text-red-600'}`}>
                                  <CheckCircle2 className={`h-3 w-3 mr-1 ${surveyCompletionStatus[selectedContract.id] ? 'text-green-500' : 'text-red-500'}`} />
                                  설문조사 {surveyCompletionStatus[selectedContract.id] ? '완료' : '미완료'}
                                </span>
                              )}
                              <span className={`flex items-center ${signatureStatus[selectedContract.id] ? 'text-green-600' : 'text-red-600'}`}>
                                <Target className={`h-3 w-3 mr-1 ${signatureStatus[selectedContract.id] ? 'text-green-500' : 'text-red-500'}`} />
                                서명 {signatureStatus[selectedContract.id] ? '완료' : '미완료'}
                              </span>
                            </div>
                          </div>
                          
                          {/* 비밀유지 계약서인 경우 추가 안내 */}
                          {selectedContract.templateName === "비밀유지 계약서" && additionalFiles.length > 0 && (
                            <p className="text-xs text-blue-600 flex items-center">
                              <FileText className="h-3 w-3 text-blue-500 mr-1" />
                              첨부 서류도 확인해주세요
                            </p>
                          )}
                        </>
                      )}
                    </div>

                    {/* 동적 버튼 영역 */}
                    <div className="flex items-center space-x-2">
                      {allCompleted ? (
                        // 모든 계약서 완료시
                        <Button
                          className="gap-2 bg-green-600 hover:bg-green-700 transition-colors"
                          onClick={completeAllSigns}
                        >
                          <Trophy className="h-4 w-4" />
                          모든 서명 완료
                        </Button>
                      ) : currentContractStatus?.status === 'completed' ? (
                        // 현재 계약서가 완료된 경우
                        <Button
                          variant="outline"
                          className="gap-2"
                          onClick={() => {
                            const nextContract = getNextPendingContract();
                            if (nextContract) {
                              setSelectedContract(nextContract);
                            }
                          }}
                          disabled={!getNextPendingContract()}
                        >
                          <ArrowRight className="h-4 w-4" />
                          다음 계약서
                        </Button>
                      ) : (
                        // 현재 계약서를 서명해야 하는 경우
                        <Button
                          className={`gap-2 transition-colors ${
                            canCompleteCurrentContract 
                              ? "bg-blue-600 hover:bg-blue-700" 
                              : "bg-gray-400 cursor-not-allowed"
                          }`}
                          onClick={completeSign}
                          disabled={!canCompleteCurrentContract || isSubmitting} // 🔥 조건 수정
                        >
                          {isSubmitting ? (
                            <>
                              <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                              </svg>
                              처리중...
                            </>
                          ) : (
                            <>
                              <FileSignature className="h-4 w-4" />
                              서명 완료
                              {totalCount > 1 && (
                                <span className="ml-1 text-xs">
                                  ({completedCount + 1}/{totalCount})
                                </span>
                              )}
                            </>
                          )}
                        </Button>
                      )}
                    </div>
                  </div>
                </>
              ) : (
                <div className="flex flex-col items-center justify-center h-full text-center p-6">
                  <div className="bg-blue-50 p-6 rounded-full mb-4">
                    <FileSignature className="h-12 w-12 text-blue-500" />
                  </div>
                  <h3 className="text-xl font-medium text-gray-800 mb-2">{t("basicContracts.dialog.selectDocument")}</h3>
                  <p className="text-gray-500 max-w-md">
                    {t("basicContracts.dialog.selectDocumentDescription")}
                  </p>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}