summaryrefslogtreecommitdiff
path: root/components/ship-vendor-document/user-vendor-document-table-container.tsx
blob: 61d52c282b0ba681f24b3945919515014b6506a7 (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
// user-vendor-document-display.tsx
"use client"

import React from "react"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Building, FileText, AlertCircle, Eye, Download, Loader2, Plus, Trash2, Edit } from "lucide-react"
import { SimplifiedDocumentsTable } from "@/lib/vendor-document-list/ship/enhanced-documents-table"
import {
  getUserVendorDocuments,
  getUserVendorDocumentStats,
} from "@/lib/vendor-document-list/enhanced-document-service"
import { SimplifiedDocumentsView } from "@/db/schema"
import { WebViewerInstance } from "@pdftron/webviewer"
import { NewRevisionDialog } from "./new-revision-dialog"
import { useRouter } from 'next/navigation'
import { AddAttachmentDialog } from "./add-attachment-dialog" // ✅ import 추가
import { EditRevisionDialog } from "./edit-revision-dialog" // ✅ 추가

/* -------------------------------------------------------------------------------------------------
 * Types & Constants
 * -----------------------------------------------------------------------------------------------*/
interface UserVendorDocumentDisplayProps {
  allPromises: Promise<[
    Awaited<ReturnType<typeof getUserVendorDocuments>>, // 문서 목록
    Awaited<ReturnType<typeof getUserVendorDocumentStats>>, // 통계 데이터
  ]>
}

interface StageInfo {
  id: number
  stageName: string
  stageStatus: string
  stageOrder: number
  planDate: string | null
  actualDate: string | null
  assigneeName: string | null
  priority: string
  revisions: RevisionInfo[]
}

interface RevisionInfo {
  id: number
  issueStageId: number
  revision: string
  uploaderType: string
  uploaderId: number | null
  uploaderName: string | null
  comment: string | null
  usage: string | null
  usageType: string | null
  revisionStatus: string
  submittedDate: string | null
  approvedDate: string | null
  uploadedAt: string | null
  reviewStartDate: string | null
  rejectedDate: string | null
  reviewerId: number | null
  reviewerName: string | null
  reviewComments: string | null
  createdAt: Date
  updatedAt: Date
  stageName?: string
  attachments: AttachmentInfo[]
}

interface AttachmentInfo {
  id: number
  revisionId: number
  fileName: string
  filePath: string
  dolceFilePath: string | null
  fileSize: number | null
  fileType: string | null
  createdAt: Date
  updatedAt: Date
}

interface DocumentSelectionContextType {
  selectedDocumentId: number | null
  selectedStageId: number | null
  selectedRevisionId: number | null
  setSelectedDocumentId: (id: number | null) => void
  setSelectedStageId: (id: number | null) => void
  setSelectedRevisionId: (id: number | null) => void
  allData: SimplifiedDocumentsView[] | null
  setAllData: (data: SimplifiedDocumentsView[]) => void // ✅ 추가
}

export const DocumentSelectionContext = React.createContext<DocumentSelectionContextType>(
  {
    selectedDocumentId: null,
    selectedStageId: null,
    selectedRevisionId: null,
    setSelectedDocumentId: (_id: number | null) => { },
    setSelectedStageId: (_id: number | null) => { },
    setSelectedRevisionId: (_id: number | null) => { },
    allData: null,
    setAllData: (_data: SimplifiedDocumentsView[]) => { }, // ✅ 추가
  },
)

/* -------------------------------------------------------------------------------------------------
 * Revision & Attachment Tables
 * -----------------------------------------------------------------------------------------------*/
// user-vendor-document-display.tsx의 RevisionTable 컴포넌트 수정
// B3 용도 타입 축약 표시 함수 추가

function getUsageTypeDisplay(usageType: string | null): string {
  if (!usageType) return '-'

  // B3 용도 타입 축약 표시
  const abbreviations: Record<string, string> = {
    'Approval Submission Full': 'AS-F',
    'Approval Submission Partial': 'AS-P',
    'Approval Completion Full': 'AC-F',
    'Approval Completion Partial': 'AC-P',
    'Working Full': 'W-F',
    'Working Partial': 'W-P',
    'Reference Full': 'R-F',
    'Reference Partial': 'R-P',
    'Reference Series Full': 'RS-F',
    'Reference Series Partial': 'RS-P',
  }

  return abbreviations[usageType] || usageType
}

function RevisionTable({
  revisions,
  onViewRevision,
  onNewRevision,
  onEditRevision, // ✅ 수정 함수 prop 추가
}: {
  revisions: RevisionInfo[]
  onViewRevision: (revision: RevisionInfo) => void
  onNewRevision: () => void
  onEditRevision: (revision: RevisionInfo) => void // ✅ 수정 함수 타입 추가
}) {
  const { selectedRevisionId, setSelectedRevisionId } =
    React.useContext(DocumentSelectionContext)

  const toggleSelect = (revisionId: number) => {
    setSelectedRevisionId(revisionId === selectedRevisionId ? null : revisionId)
  }

  // ✅ 리비전 수정 가능 여부 확인 함수
  const canEditRevision = React.useCallback((revision: RevisionInfo) => {
    // 첨부파일이 없으면 수정 가능
    if ((!revision.attachments || revision.attachments.length === 0)&&revision.uploaderType ==="vendor") {
      return true
    }

    // 모든 첨부파일의 dolceFilePath가 null이거나 빈값이어야 수정 가능
    return revision.attachments.every(attachment => 
      !attachment.dolceFilePath || attachment.dolceFilePath.trim() === ''
    )
  }, [])

  // ✅ 리비전 상태 표시 함수 (처리된 파일이 있는지 확인)
  const getRevisionProcessStatus = React.useCallback((revision: RevisionInfo) => {
    if (!revision.attachments || revision.attachments.length === 0) {
      return 'no-files'
    }

    const processedCount = revision.attachments.filter(attachment => 
      attachment.dolceFilePath && attachment.dolceFilePath.trim() !== ''
    ).length

    if (processedCount === 0) {
      return 'not-processed'
    } else if (processedCount === revision.attachments.length) {
      return 'fully-processed'
    } else {
      return 'partially-processed'
    }
  }, [])

  return (
    <Card className="flex-1">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-lg">Revisions</CardTitle>
          </div>
          <Button
            onClick={onNewRevision}
            size="sm"
            className="flex items-center gap-2"
          >
            <Plus className="h-4 w-4" />
            New Revision
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <div className="overflow-x-auto">
          <Table className="tbl-compact">
            <TableHeader>
              <TableRow>
                <TableHead className="w-12">Select</TableHead>
                <TableHead>Revision</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Usage</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Uploader</TableHead>
                <TableHead>Comment</TableHead>
                <TableHead>Upload Date</TableHead>
                <TableHead className="text-center">Files</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {revisions.map((revision) => {
                const canEdit = canEditRevision(revision)
                const processStatus = getRevisionProcessStatus(revision)
                
                return (
                  <TableRow
                    key={revision.id}
                    className={`revision-table-row ${selectedRevisionId === revision.id ? 'selected' : ''
                      }`}
                  >
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selectedRevisionId === revision.id}
                        onChange={() => toggleSelect(revision.id)}
                        className="h-4 w-4 cursor-pointer"
                      />
                    </TableCell>
                    <TableCell className="font-mono font-medium">
                      <div className="flex items-center gap-2">
                        {revision.revision}
                        {/* ✅ 처리 상태 인디케이터 */}
                        {processStatus === 'fully-processed' && (
                          <div 
                            className="w-2 h-2 bg-blue-500 rounded-full" 
                            title="All files processed"
                          />
                        )}
                        {processStatus === 'partially-processed' && (
                          <div 
                            className="w-2 h-2 bg-yellow-500 rounded-full" 
                            title="Some files processed"
                          />
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-sm">
                      {revision.uploaderType === "vendor" ? "To SHI" : "From SHI"}
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">
                        {revision.usage || '-'}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">
                        {revision.usageType ? (
                          revision.usageType
                        ) : (
                          <span className="text-gray-400 text-xs">-</span>
                        )}
                      </span>
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={
                          revision.revisionStatus === 'APPROVED'
                            ? 'default'
                            : 'secondary'
                        }
                        className="text-xs"
                      >
                        {revision.revisionStatus}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">{revision.uploaderName || '-'}</span>
                    </TableCell>
                    <TableCell className="py-1 px-2">
                      {revision.comment ? (
                        <div className="max-w-24">
                          <p className="text-xs text-gray-700 bg-gray-50 p-1 rounded truncate" title={revision.comment}>
                            {revision.comment}
                          </p>
                        </div>
                      ) : (
                        <span className="text-gray-400 text-xs">-</span>
                      )}
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">
                        {revision.uploadedAt
                          ? new Date(revision.uploadedAt).toLocaleDateString()
                          : '-'}
                      </span>
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex items-center justify-center gap-1">
                        <span>{revision.attachments.length}</span>
                        {/* ✅ 처리된 파일 수 표시 */}
                        {processStatus === 'partially-processed' && (
                          <span className="text-xs text-gray-500">
                            ({revision.attachments.filter(att => 
                              att.dolceFilePath && att.dolceFilePath.trim() !== ''
                            ).length} processed)
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        {/* 보기 버튼 */}
                        {revision.attachments.length > 0 && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => onViewRevision(revision)}
                            className="h-8 px-2"
                            title="View attachments"
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                        )}
                        
                        {/* ✅ 수정 버튼 */}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => onEditRevision(revision)}
                          className={`h-8 px-2 ${
                            canEdit 
                              ? 'text-blue-600 hover:text-blue-700 hover:bg-blue-50' 
                              : 'text-gray-400 cursor-not-allowed'
                          }`}
                          disabled={!canEdit}
                          title={
                            canEdit 
                              ? 'Edit revision' 
                              : 'Cannot edit - some files have been processed'
                          }
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  )
}

function AttachmentTable({
  attachments,
  onDownloadFile,
  onDeleteFile, // ✅ 삭제 함수 prop 추가
}: {
  attachments: AttachmentInfo[]
  onDownloadFile: (attachment: AttachmentInfo) => void
  onDeleteFile: (attachment: AttachmentInfo) => Promise<void> // ✅ 삭제 함수 추가
}) {
  const { selectedRevisionId, allData, setAllData } = React.useContext(DocumentSelectionContext)
  const [addAttachmentDialogOpen, setAddAttachmentDialogOpen] = React.useState(false)
  const [deletingFileId, setDeletingFileId] = React.useState<number | null>(null) // ✅ 삭제 중인 파일 ID
  const router = useRouter()

  // 선택된 리비전 정보 가져오기
  const selectedRevisionInfo = React.useMemo(() => {
    if (!selectedRevisionId || !allData) return null

    for (const doc of allData) {
      if (doc.allStages) {
        for (const stage of doc.allStages as StageInfo[]) {
          const revision = stage.revisions.find(r => r.id === selectedRevisionId)
          if (revision) return revision
        }
      }
    }
    return null
  }, [selectedRevisionId, allData])

  // 첨부파일 추가 핸들러
  const handleAddAttachment = React.useCallback(() => {
    if (selectedRevisionInfo) {
      setAddAttachmentDialogOpen(true)
    }
  }, [selectedRevisionInfo])

  // ✅ 삭제 가능 여부 확인 함수
  const canDeleteFile = React.useCallback((attachment: AttachmentInfo) => {
    return !attachment.dolceFilePath || attachment.dolceFilePath.trim() === ''
  }, [])

  // ✅ 파일 삭제 핸들러
  const handleDeleteFile = React.useCallback(async (attachment: AttachmentInfo) => {
    if (!canDeleteFile(attachment)) {
      alert('This file cannot be deleted because it has been processed by the system.')
      return
    }

    const confirmDelete = window.confirm(
      `Are you sure you want to delete "${attachment.fileName}"?\nThis action cannot be undone.`
    )
    
    if (!confirmDelete) return

    try {
      setDeletingFileId(attachment.id)
      await onDeleteFile(attachment)
    } catch (error) {
      console.error('Delete file error:', error)
      alert(`Failed to delete file: ${error instanceof Error ? error.message : 'Unknown error'}`)
    } finally {
      setDeletingFileId(null)
    }
  }, [canDeleteFile, onDeleteFile])

  // 첨부파일 업로드 성공 핸들러
  const handleAttachmentUploadSuccess = React.useCallback((uploadResult?: any) => {
    if (!selectedRevisionId || !allData || !uploadResult?.data) {
      console.log('🔄 Full refresh')
      router.refresh()
      return
    }

    try {
      // 새로운 첨부파일들을 AttachmentInfo 형태로 변환
      const newAttachments: AttachmentInfo[] = uploadResult.data.uploadedFiles?.map((file: any) => ({
        id: file.id,
        revisionId: selectedRevisionId,
        fileName: file.fileName,
        filePath: file.filePath,
        dolceFilePath: null, // ✅ 새 파일은 dolceFilePath가 없음
        fileSize: file.fileSize,
        fileType: file.fileType || null,
        createdAt: new Date(),
        updatedAt: new Date(),
      })) || []

      // allData에서 해당 리비전을 찾아서 첨부파일 추가
      const updatedData = allData.map(doc => {
        const updatedDoc = { ...doc }

        if (updatedDoc.allStages) {
          const stages = [...updatedDoc.allStages as StageInfo[]]

          for (const stage of stages) {
            const revisionIndex = stage.revisions.findIndex(r => r.id === selectedRevisionId)
            if (revisionIndex !== -1) {
              // 해당 리비전의 첨부파일 배열에 새 파일들 추가
              stage.revisions[revisionIndex] = {
                ...stage.revisions[revisionIndex],
                attachments: [...stage.revisions[revisionIndex].attachments, ...newAttachments]
              }
              updatedDoc.allStages = stages
              break
            }
          }
        }

        return updatedDoc
      })

      setAllData(updatedData)
      console.log('✅ AttachmentTable update complete')

      // 메인 테이블도 업데이트 (약간의 지연 후)
      setTimeout(() => {
        router.refresh()
      }, 1500)

    } catch (error) {
      console.error('❌ AttachmentTable update failed:', error)
      router.refresh()
    }
  }, [selectedRevisionId, allData, setAllData, router])

  return (
    <>
      <Card className="w-96 flex-shrink-0">
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg">Attachments</CardTitle>
            {/* + 버튼 */}
            {selectedRevisionId && selectedRevisionInfo && (
              <Button
                onClick={handleAddAttachment}
                size="sm"
                variant="outline"
                className="flex items-center gap-2"
              >
                <Plus className="h-4 w-4" />
                Add
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <Table className="tbl-compact">
            <TableHeader>
              <TableRow>
                <TableHead>File Name</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {!selectedRevisionId || attachments.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={2} className="h-24 text-center">
                    <div className="flex flex-col items-center gap-2 text-muted-foreground">
                      <FileText className="h-8 w-8" />
                      <span>
                        {!selectedRevisionId
                          ? 'Please select a revision'
                          : 'No attached files'}
                      </span>
                      {/* 리비전이 선택된 경우 추가 버튼 표시 */}
                      {selectedRevisionId && selectedRevisionInfo && (
                        <Button
                          onClick={handleAddAttachment}
                          size="sm"
                          variant="outline"
                          className="mt-2"
                        >
                          <Plus className="h-4 w-4 mr-2" />
                          Add First File
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ) : (
                attachments.map((file) => (
                  <TableRow key={file.id}>
                    <TableCell className="font-medium">
                      <div>
                        <div className="truncate max-w-[180px]" title={file.fileName}>
                          {file.fileName}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {file.fileSize
                            ? file.fileSize >= 1024 * 1024
                              ? `${(file.fileSize / 1024 / 1024).toFixed(1)}MB`
                              : `${(file.fileSize / 1024).toFixed(1)}KB`
                            : '-'}
                        </div>
                        {/* ✅ dolceFilePath 상태 표시 */}
                        {file.dolceFilePath && file.dolceFilePath.trim() !== '' && (
                          <div className="text-xs text-blue-600 font-medium">
                            Processed
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        {/* 다운로드 버튼 */}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => onDownloadFile(file)}
                          className="h-8 px-2"
                          title="Download file"
                        >
                          <Download className="h-4 w-4" />
                        </Button>
                        
                        {/* ✅ 삭제 버튼 */}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteFile(file)}
                          className={`h-8 px-2 ${
                            canDeleteFile(file) 
                              ? 'text-red-600 hover:text-red-700 hover:bg-red-50' 
                              : 'text-gray-400 cursor-not-allowed'
                          }`}
                          disabled={!canDeleteFile(file) || deletingFileId === file.id}
                          title={
                            canDeleteFile(file) 
                              ? 'Delete file' 
                              : 'Cannot delete processed file'
                          }
                        >
                          {deletingFileId === file.id ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <Trash2 className="h-4 w-4" />
                          )}
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* AddAttachmentDialog */}
      {selectedRevisionInfo && (
        <AddAttachmentDialog
          open={addAttachmentDialogOpen}
          onOpenChange={setAddAttachmentDialogOpen}
          revisionId={selectedRevisionId!}
          revisionName={selectedRevisionInfo.revision}
          onSuccess={handleAttachmentUploadSuccess}
        />
      )}
    </>
  )
}

// SubTables 컴포넌트 - 중복 정의 제거 및 통합
function SubTables() {
  const router = useRouter()
  const { selectedDocumentId, selectedRevisionId, setSelectedRevisionId, allData, setAllData } =
    React.useContext(DocumentSelectionContext)

  // PDF 뷰어 상태 관리
  const [viewerOpen, setViewerOpen] = React.useState(false)
  const [selectedRevision, setSelectedRevision] = React.useState<RevisionInfo | null>(null)
  const [instance, setInstance] = React.useState<WebViewerInstance | null>(null)
  const [viewerLoading, setViewerLoading] = React.useState(true)
  const [fileSetLoading, setFileSetLoading] = React.useState(true)
  const viewer = React.useRef<HTMLDivElement>(null)
  const initialized = React.useRef(false)
  const isCancelled = React.useRef(false)

  const [newRevisionDialogOpen, setNewRevisionDialogOpen] = React.useState(false)
  
  // ✅ 리비전 수정 다이얼로그 상태
  const [editRevisionDialogOpen, setEditRevisionDialogOpen] = React.useState(false)
  const [editingRevision, setEditingRevision] = React.useState<RevisionInfo | null>(null)

  const handleNewRevision = React.useCallback(() => {
    setNewRevisionDialogOpen(true)
  }, [])

  // ✅ 리비전 수정 핸들러
  const handleEditRevision = React.useCallback((revision: RevisionInfo) => {
    setEditingRevision(revision)
    setEditRevisionDialogOpen(true)
  }, [])

  // ✅ 리비전 수정 성공 핸들러
  const handleRevisionEditSuccess = React.useCallback((action: 'update' | 'delete', result?: any) => {
    if (!allData || !editingRevision) {
      // fallback: 전체 새로고침
      setTimeout(() => router.refresh(), 500)
      return
    }

    try {
      if (action === 'delete') {
        // 리비전 삭제: allData에서 해당 리비전 제거
        const updatedData = allData.map(doc => {
          const updatedDoc = { ...doc }

          if (updatedDoc.allStages) {
            const stages = [...updatedDoc.allStages as StageInfo[]]

            for (const stage of stages) {
              const revisionIndex = stage.revisions.findIndex(r => r.id === editingRevision.id)
              if (revisionIndex !== -1) {
                // 해당 리비전 제거
                stage.revisions.splice(revisionIndex, 1)
                updatedDoc.allStages = stages
                break
              }
            }
          }

          return updatedDoc
        })

        setAllData(updatedData)

        // 삭제된 리비전이 선택되어 있었으면 선택 해제
        if (selectedRevisionId === editingRevision.id) {
          setSelectedRevisionId(null)
        }

        console.log('✅ Revision deleted and state updated')

      } else if (action === 'update') {
        // 리비전 업데이트: allData에서 해당 리비전 정보 수정
        const updatedData = allData.map(doc => {
          const updatedDoc = { ...doc }

          if (updatedDoc.allStages) {
            const stages = [...updatedDoc.allStages as StageInfo[]]

            for (const stage of stages) {
              const revisionIndex = stage.revisions.findIndex(r => r.id === editingRevision.id)
              if (revisionIndex !== -1) {
                // 해당 리비전 업데이트
                stage.revisions[revisionIndex] = {
                  ...stage.revisions[revisionIndex],
                  comment: result?.updatedRevision?.comment || stage.revisions[revisionIndex].comment,
                  usage: result?.updatedRevision?.usage || stage.revisions[revisionIndex].usage,
                  usageType: result?.updatedRevision?.usageType || stage.revisions[revisionIndex].usageType,
                  updatedAt: new Date(),
                }
                updatedDoc.allStages = stages
                break
              }
            }
          }

          return updatedDoc
        })

        setAllData(updatedData)
        console.log('✅ Revision updated and state updated')
      }

      // 약간의 지연 후 서버 데이터 새로고침
      setTimeout(() => {
        router.refresh()
      }, 1000)

    } catch (error) {
      console.error('❌ Revision edit state update failed:', error)
      // 실패 시 전체 새로고침
      setTimeout(() => router.refresh(), 500)
    }
  }, [allData, editingRevision, setAllData, selectedRevisionId, setSelectedRevisionId, router])

  // 파일 삭제 함수
  const handleDeleteFile = React.useCallback(async (attachment: AttachmentInfo) => {
    try {
      const response = await fetch(`/api/attachment-delete`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          attachmentId: attachment.id,
          revisionId: attachment.revisionId,
        }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || 'Failed to delete file.')
      }

      // 성공시 로컬 상태 업데이트
      if (allData && selectedRevisionId) {
        const updatedData = allData.map(doc => {
          const updatedDoc = { ...doc }

          if (updatedDoc.allStages) {
            const stages = [...updatedDoc.allStages as StageInfo[]]

            for (const stage of stages) {
              const revisionIndex = stage.revisions.findIndex(r => r.id === selectedRevisionId)
              if (revisionIndex !== -1) {
                // 해당 리비전에서 첨부파일 제거
                stage.revisions[revisionIndex] = {
                  ...stage.revisions[revisionIndex],
                  attachments: stage.revisions[revisionIndex].attachments.filter(
                    att => att.id !== attachment.id
                  )
                }
                updatedDoc.allStages = stages
                break
              }
            }
          }

          return updatedDoc
        })

        setAllData(updatedData)
        console.log('✅ File deleted and state updated')
      }

      // 약간의 지연 후 서버 데이터 새로고침
      setTimeout(() => {
        router.refresh()
      }, 1000)

    } catch (error) {
      console.error('Delete file error:', error)
      throw error // AttachmentTable에서 에러 핸들링
    }
  }, [allData, selectedRevisionId, setAllData, router])

  const handleRevisionUploadSuccess = React.useCallback(async (uploadResult?: any) => {
    if (!selectedDocumentId || !allData || !uploadResult?.data) {
      // fallback: 전체 새로고침
      window.location.reload()
      return
    }

    try {
      // 새로 업로드된 리비전 정보 구성
      const newRevision: RevisionInfo = {
        id: uploadResult.data.revisionId,
        issueStageId: uploadResult.data.issueStageId,
        revision: uploadResult.data.revision,
        uploaderType: "vendor",
        uploaderId: null,
        uploaderName: uploadResult.data.uploaderName || null,
        comment: uploadResult.data.comment || null,
        usage: uploadResult.data.usage,
        usageType: uploadResult.data.usageType || null,
        revisionStatus: "UPLOADED",
        submittedDate: null,
        approvedDate: null,
        uploadedAt: new Date().toISOString().slice(0, 10),
        reviewStartDate: null,
        rejectedDate: null,
        reviewerId: null,
        reviewerName: null,
        reviewComments: null,
        createdAt: new Date(),
        updatedAt: new Date(),
        stageName: uploadResult.data.stage,
        attachments: uploadResult.data.uploadedFiles?.map((file: any) => ({
          id: file.id,
          revisionId: uploadResult.data.revisionId,
          fileName: file.fileName,
          filePath: file.filePath,
          dolceFilePath: null,
          fileSize: file.fileSize,
          fileType: file.fileType || null,
          createdAt: new Date(),
          updatedAt: new Date(),
        })) || []
      }

      // allData에서 해당 문서 찾아서 업데이트
      const updatedData = allData.map(doc => {
        if (doc.documentId === selectedDocumentId) {
          const updatedDoc = { ...doc }

          // allStages가 있으면 해당 stage에 새 revision 추가
          if (updatedDoc.allStages) {
            const stages = [...updatedDoc.allStages as StageInfo[]]
            const targetStage = stages.find(stage =>
              stage.stageName === uploadResult.data.stage ||
              stage.stageName === uploadResult.data.usage
            )

            if (targetStage) {
              // 기존 revision과 중복 체크 (같은 revision, usage, usageType)
              const isDuplicate = targetStage.revisions.some(rev =>
                rev.revision === newRevision.revision &&
                rev.usage === newRevision.usage &&
                rev.usageType === newRevision.usageType
              )

              if (!isDuplicate) {
                targetStage.revisions = [newRevision, ...targetStage.revisions]
                updatedDoc.allStages = stages
              }
            } else {
              // 첫 번째 stage에 추가 (fallback)
              if (stages.length > 0) {
                stages[0].revisions = [newRevision, ...stages[0].revisions]
                updatedDoc.allStages = stages
              }
            }
          }

          return updatedDoc
        }
        return doc
      })

      // State 업데이트
      setAllData(updatedData)

      console.log('✅ RevisionTable data update complete')

    } catch (error) {
      console.error('❌ RevisionTable update failed:', error)
      // 실패 시 전체 새로고침
      window.location.reload()
    }

    setTimeout(() => {
      router.refresh() // 서버 컴포넌트 재렌더링으로 최신 데이터 가져오기
    }, 1500) // 1.5초 후 새로고침 (사용자가 업데이트를 확인할 시간)

  }, [selectedDocumentId, allData, setAllData, router])

  const selectedDocument = React.useMemo(() => {
    if (!selectedDocumentId || !allData) return null
    return allData.find((d) => d.documentId === selectedDocumentId) || null
  }, [selectedDocumentId, allData])

  // 선택된 문서의 모든 스테이지에서 모든 리비전을 수집
  const allRevisions = React.useMemo(() => {
    if (!selectedDocument?.allStages) return []

    const revisions: RevisionInfo[] = []
    for (const stage of selectedDocument.allStages as StageInfo[]) {
      // 각 리비전에 스테이지 이름 추가
      const stageRevisions = stage.revisions.map(revision => ({
        ...revision,
        stageName: stage.stageName
      }))
      revisions.push(...stageRevisions)
    }

    // 생성 날짜순으로 정렬 (최신순)
    return revisions.sort((a, b) =>
      new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    )
  }, [selectedDocument])

  const selectedRevisionData = React.useMemo(() => {
    if (!selectedRevisionId) return null
    return allRevisions.find(r => r.id === selectedRevisionId) || null
  }, [selectedRevisionId, allRevisions])

  // PDF 뷰어 정리 함수
  const cleanupHtmlStyle = React.useCallback(() => {
    const htmlElement = window.document.documentElement
    const originalStyle = htmlElement.getAttribute("style") || ""
    const colorSchemeStyle = originalStyle
      .split(";")
      .map((s) => s.trim())
      .find((s) => s.startsWith("color-scheme:"))

    if (colorSchemeStyle) {
      htmlElement.setAttribute("style", colorSchemeStyle + ";")
    } else {
      htmlElement.removeAttribute("style")
    }
  }, [])

  // 문서 뷰어 열기 함수
  const handleViewRevision = React.useCallback((revision: RevisionInfo) => {
    setSelectedRevision(revision)
    setViewerOpen(true)
    setViewerLoading(true)
    setFileSetLoading(true)
    initialized.current = false
  }, [])

  // 파일 다운로드 함수
  const handleDownloadFile = React.useCallback(async (attachment: AttachmentInfo) => {
    try {
      const queryParam = attachment.id
        ? `id=${encodeURIComponent(attachment.id)}`
        : `path=${encodeURIComponent(attachment.filePath)}`

      const response = await fetch(`/api/document-download?${queryParam}`)

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || 'Failed to download file.')
      }

      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = window.document.createElement('a')
      link.href = url
      link.download = attachment.fileName
      window.document.body.appendChild(link)
      link.click()
      window.document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error('File download error:', error)
      alert(`File download failed: ${error instanceof Error ? error.message : 'Unknown error'}`)
    }
  }, [])

  // WebViewer 초기화
  React.useEffect(() => {
    if (viewerOpen && !initialized.current) {
      initialized.current = true
      isCancelled.current = false

      requestAnimationFrame(() => {
        if (viewer.current && !isCancelled.current) {
          import("@pdftron/webviewer").then(({ default: WebViewer }) => {
            if (isCancelled.current) {
              console.log("WebViewer initialization cancelled (Dialog closed)")
              return
            }

            WebViewer(
              {
                path: "/pdftronWeb",
                licenseKey: "demo:1739264618684:616161d7030000000091db1c97c6f386d41d3506ab5b507381ef2ee2bd",
                fullAPI: true,
                css: "/globals.css",
              },
              viewer.current as HTMLDivElement
            ).then(async (instance: WebViewerInstance) => {
              if (!isCancelled.current) {
                setInstance(instance)
                instance.UI.enableFeatures([instance.UI.Feature.MultiTab])
                instance.UI.disableElements(["addTabButton", "multiTabsEmptyPage"])
                setViewerLoading(false)
              }
            })
          })
        }
      })
    }

    return () => {
      if (instance) {
        instance.UI.dispose()
      }
      setTimeout(() => cleanupHtmlStyle(), 500)
    }
  }, [viewerOpen, cleanupHtmlStyle, instance])

  // 문서 로드
  React.useEffect(() => {
    const loadDocument = async () => {
      if (instance && selectedRevision?.attachments?.length) {
        const { UI } = instance

        const tabIds = []
        for (const attachment of selectedRevision.attachments) {
          try {
            const response = await fetch(attachment.filePath)
            const blob = await response.blob()
            const options = {
              filename: attachment.fileName,
              ...(attachment.fileType?.includes("xlsx") && {
                officeOptions: {
                  formatOptions: {
                    applyPageBreaksToSheet: true,
                  },
                },
              }),
            }
            const tab = await UI.TabManager.addTab(blob, options)
            tabIds.push(tab)
          } catch (error) {
            console.error("File load failed:", attachment.filePath, error)
          }
        }

        if (tabIds.length > 0) {
          await UI.TabManager.setActiveTab(tabIds[0])
        }

        setFileSetLoading(false)
      }
    }
    loadDocument()
  }, [instance, selectedRevision])

  // 뷰어 닫기
  const handleCloseViewer = React.useCallback(async () => {
    if (!fileSetLoading) {
      isCancelled.current = true

      if (instance) {
        try {
          await instance.UI.dispose()
          setInstance(null)
        } catch (e) {
          console.warn("dispose error", e)
        }
      }

      setViewerLoading(false)
      setViewerOpen(false)
      setTimeout(() => cleanupHtmlStyle(), 1000)
    }
  }, [fileSetLoading, instance, cleanupHtmlStyle])

  if (!selectedDocument) return null

  return (
    <>
      <div className="flex gap-4">
        <RevisionTable
          revisions={allRevisions}
          onViewRevision={handleViewRevision}
          onNewRevision={handleNewRevision}
          onEditRevision={handleEditRevision} // ✅ 수정 함수 전달
        />
        <AttachmentTable
          attachments={selectedRevisionData?.attachments || []}
          onDownloadFile={handleDownloadFile}
          onDeleteFile={handleDeleteFile}
        />
      </div>

      {/* 통합된 문서 뷰어 다이얼로그 */}
      <Dialog open={viewerOpen} onOpenChange={handleCloseViewer}>
        <DialogContent className="w-[90vw] h-[90vh]" style={{ maxWidth: "none" }}>
          <DialogHeader className="h-[38px]">
            <DialogTitle>Document Preview</DialogTitle>
            <DialogDescription>
              Revision {selectedRevision?.revision} attachments
            </DialogDescription>
          </DialogHeader>
          <div
            ref={viewer}
            style={{ height: "calc(90vh - 20px - 38px - 1rem - 48px)" }}
          >
            {viewerLoading && (
              <div className="flex flex-col items-center justify-center py-12">
                <Loader2 className="h-8 w-8 text-blue-500 animate-spin mb-4" />
                <p className="text-sm text-muted-foreground">
                  Loading document viewer...
                </p>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>

      <NewRevisionDialog
        open={newRevisionDialogOpen}
        onOpenChange={setNewRevisionDialogOpen}
        documentId={selectedDocument.documentId}
        documentTitle={selectedDocument.title}
        drawingKind={selectedDocument.drawingKind || 'B4'}
        onSuccess={handleRevisionUploadSuccess}
      />

      {/* ✅ 리비전 수정 다이얼로그 */}
      <EditRevisionDialog
        open={editRevisionDialogOpen}
        onOpenChange={setEditRevisionDialogOpen}
        revision={editingRevision}
        onSuccess={handleRevisionEditSuccess}
      />
    </>
  )
}

/* -------------------------------------------------------------------------------------------------
 * High‑level Selected Document Summary
 * -----------------------------------------------------------------------------------------------*/
function SelectedDocumentInfo() {
  const { selectedDocumentId, selectedRevisionId, allData } =
    React.useContext(DocumentSelectionContext)

  if (!selectedDocumentId || !allData) return null

  const doc = allData.find((d) => d.documentId === selectedDocumentId)
  if (!doc) return null

  const totalRevisions = doc.allStages
    ? (doc.allStages as StageInfo[]).reduce(
      (acc, s) => acc + s.revisions.length,
      0,
    )
    : 0

  let selectedRevision: RevisionInfo | null = null
  if (selectedRevisionId && doc.allStages) {
    for (const stage of doc.allStages as StageInfo[]) {
      const rev = stage.revisions.find((r) => r.id === selectedRevisionId)
      if (rev) {
        selectedRevision = rev
        break
      }
    }
  }

  return (
    <div className="flex flex-wrap items-center gap-3 rounded-lg bg-gray-50 p-4">
      <div className="flex items-center gap-2">
        <Badge variant="secondary" className="text-sm">
          Document: {doc.docNumber}
        </Badge>
        <span className="max-w-[300px] truncate text-sm font-medium text-gray-700">
          {doc.title}
        </span>
      </div>
      <div className="flex items-center gap-2 text-sm text-gray-600">
        <span>•</span>
        <span>Total {totalRevisions} revisions</span>
        {selectedRevision && (
          <>
            <span>•</span>
            <Badge variant="outline" className="text-sm">
              Selected revision: {selectedRevision.revision}
            </Badge>
            <span>({selectedRevision.attachments.length} files)</span>
          </>
        )}
      </div>
    </div>
  )
}

/* -------------------------------------------------------------------------------------------------
 * Main Exported Component
 * -----------------------------------------------------------------------------------------------*/
export function UserVendorDocumentDisplay({
  allPromises,
}: UserVendorDocumentDisplayProps) {
  /**
   * Selection state
   */
  const [selectedDocumentId, setSelectedDocumentId] =
    React.useState<number | null>(null)
  const [selectedStageId, setSelectedStageId] = React.useState<number | null>(
    null,
  )
  const [selectedRevisionId, setSelectedRevisionId] =
    React.useState<number | null>(null)
  const [allData, setAllData] =
    React.useState<SimplifiedDocumentsView[] | null>(null)

  const handleDocumentSelect = React.useCallback((id: number | null) => {
    setSelectedDocumentId(id)
    setSelectedStageId(null)
    setSelectedRevisionId(null)
  }, [])

  const ctx = React.useMemo<DocumentSelectionContextType>(
    () => ({
      selectedDocumentId,
      selectedStageId,
      selectedRevisionId,
      setSelectedDocumentId: handleDocumentSelect,
      setSelectedStageId,
      setSelectedRevisionId,
      allData,
      setAllData, // ✅ 추가
    }),
    [
      selectedDocumentId,
      selectedStageId,
      selectedRevisionId,
      handleDocumentSelect,
      allData,
      setAllData, // ✅ 의존성 배열에 추가
    ],
  )

  if (!allPromises) {
    return (
      <Card>
        <CardContent className="flex items-center justify-center py-8">
          <div className="text-center">
            <AlertCircle className="mx-auto mb-2 h-8 w-8 text-gray-400" />
            <p className="text-gray-600">Unable to load data.</p>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <DocumentSelectionContext.Provider value={ctx}>
      <div className="space-y-4">
        <Card>
          <CardContent className="flex items-center justify-center py-8">
            <SimplifiedDocumentsTable
              allPromises={allPromises}
              onDataLoaded={setAllData}
              onDocumentSelect={handleDocumentSelect}
            />
          </CardContent>
        </Card>
        <SelectedDocumentInfo />

        <SubTables />
      </div>
    </DocumentSelectionContext.Provider>
  )
}