summaryrefslogtreecommitdiff
path: root/lib/dolce/dialogs/add-and-modify-detail-drawing-dialog.tsx
blob: 2d2532d7cdbe1cde41fe47c4f4b67884b857be58 (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
"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Textarea } from "@/components/ui/textarea";
import { Upload, X, FileIcon, Info, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "@/i18n/client";
import { UnifiedDwgReceiptItem, DetailDwgReceiptItem, editDetailDwgReceipt, fetchDetailDwgReceiptList } from "../actions";
import { v4 as uuidv4 } from "uuid";
import { useFileUploadWithProgress } from "../hooks/use-file-upload-with-progress";
import { uploadFilesWithProgress } from "../utils/upload-with-progress";
import { FileUploadProgressList } from "../components/file-upload-progress-list";
import { 
  getB3DrawingUsageOptions, 
  getB3RegisterKindOptions,
  getB4DrawingUsageOptions,
  getB4RegisterKindOptions,
  findRegisterKindCode
} from "../utils/code-translator";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter as AlertDialogFooterComponent,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface AddAndModifyDetailDrawingDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  drawing: UnifiedDwgReceiptItem | null;
  vendorCode: string;
  userId: string;
  userName: string;
  userEmail: string;
  onComplete: () => void;
  drawingKind: "B3" | "B4";
  lng: string;
  mode?: "add" | "edit";
  detailDrawing?: DetailDwgReceiptItem | null;
}

export function AddAndModifyDetailDrawingDialog({
  open,
  onOpenChange,
  drawing,
  vendorCode,
  userId,
  userName,
  userEmail,
  onComplete,
  drawingKind,
  lng,
  mode = "add",
  detailDrawing = null,
}: AddAndModifyDetailDrawingDialogProps) {
  const { t } = useTranslation(lng, "dolce");
  const [drawingUsage, setDrawingUsage] = useState<string>("");
  const [registerKind, setRegisterKind] = useState<string>("");
  const [revision, setRevision] = useState<string>("");
  const [revisionError, setRevisionError] = useState<string>("");
  const [comment, setComment] = useState<string>("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const [showConfirmation, setShowConfirmation] = useState(false);
  
  // 삭제 관련 상태
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // Edit 모드일 때 초기값 설정
  useEffect(() => {
    if (mode === "edit" && detailDrawing && open) {
      setDrawingUsage(detailDrawing.DrawingUsage || "");
      setRegisterKind(findRegisterKindCode(detailDrawing.RegisterKind || "", drawingKind));
      setRevision(detailDrawing.DrawingRevNo || "");
      setComment(detailDrawing.RegisterDesc || "");
    } else if (mode === "add" && open) {
      // Add 모드로 열릴 때는 초기화
      resetForm();
    }
  }, [mode, detailDrawing, open]);

  // 옵션 생성 (다국어 지원)
  const drawingUsageOptions = drawingKind === "B3" 
    ? getB3DrawingUsageOptions(lng)
    : getB4DrawingUsageOptions(lng);

  const registerKindOptions = drawingKind === "B3"
    ? getB3RegisterKindOptions(drawingUsage, lng).map(opt => ({
        ...opt,
        revisionRule: lng === "ko" ? "예: A, B, C 또는 R00, R01, R02" : "e.g. A, B, C or R00, R01, R02"
      }))
    : getB4RegisterKindOptions(drawingUsage, lng).map(opt => ({
        ...opt,
        revisionRule: lng === "ko" ? "예: R00, R01, R02, R03" : "e.g. R00, R01, R02, R03"
      }));

  // 파일 업로드 훅 사용 (진행도 추적)
  const {
    fileProgresses,
    files,
    removeFile,
    clearFiles,
    updateFileProgress,
    getRootProps,
    getInputProps,
    isDragActive,
  } = useFileUploadWithProgress();

  // Revision 유효성 검증 함수
  const validateRevision = (value: string): string => {
    if (!value.trim()) {
      return t("addDetailDialog.revisionRequired");
    }

    const upperValue = value.toUpperCase().trim();

    // A-Z 패턴 (단일 알파벳)
    if (/^[A-Z]$/.test(upperValue)) {
      return "";
    }

    // R00-R99 패턴
    if (/^R\d{2}$/.test(upperValue)) {
      return "";
    }

    return t("addDetailDialog.revisionInvalidFormat");
  };

  // Revision 입력 핸들러
  const handleRevisionChange = (value: string) => {
    const processedValue = value.toUpperCase();
    setRevision(processedValue);

    // 값이 있을 때만 validation
    if (processedValue.trim()) {
      const error = validateRevision(processedValue);
      setRevisionError(error);
    } else {
      setRevisionError("");
    }
  };

  // 폼 초기화
  const resetForm = useCallback(() => {
    setDrawingUsage("");
    setRegisterKind("");
    setRevision("");
    setRevisionError("");
    setComment("");
    clearFiles();
    setShowConfirmation(false);
  }, [clearFiles]);

  // 제출 (확인 단계 포함)
  const handleSubmit = async () => {
    // 유효성 검사
    if (!registerKind) {
      toast.error(t("addDetailDialog.selectRegisterKindError"));
      return;
    }
    
    if (drawingUsage !== "CMT") {
      if (!revision.trim()) {
        toast.error(t("addDetailDialog.selectRevisionError"));
        setRevisionError(t("addDetailDialog.revisionRequired"));
        return;
      }
      
      // Revision 형식 검증
      const revisionValidationError = validateRevision(revision);
      if (revisionValidationError) {
        toast.error(revisionValidationError);
        setRevisionError(revisionValidationError);
        return;
      }
    }
    
    // Add 모드일 때만 파일 필수
    if (mode === "add") {
      if (!drawing) return;
      if (!drawingUsage) {
        toast.error(t("addDetailDialog.selectDrawingUsageError"));
        return;
      }
      if (files.length === 0) {
        toast.error(t("addDetailDialog.selectFilesError"));
        return;
      }
    }

    // Edit 모드일 때는 detailDrawing 필수
    if (mode === "edit" && !detailDrawing) {
      toast.error(t("editDetailDialog.editError"));
      return;
    }

    // 확인 단계가 아니면 확인 단계로 이동
    if (!showConfirmation) {
      setShowConfirmation(true);
      return;
    }

    try {
      setIsSubmitting(true);

      if (mode === "add" && drawing) {
        // 상세도면 리스트 조회하여 RegisterSerialNo 계산
        let nextSerialNo = 1;
        try {
          const detailList = await fetchDetailDwgReceiptList({
            project: drawing.ProjectNo,
            drawingNo: drawing.DrawingNo,
            discipline: drawing.Discipline,
            drawingKind: drawing.DrawingKind,
            userId: userId,
          });

          if (detailList && detailList.length > 0) {
            // RegisterSerialNo의 최댓값을 찾아 +1 (기본값 0 처리)
            const maxSerial = Math.max(...detailList.map(item => item.RegisterSerialNo || 0));
            nextSerialNo = maxSerial + 1;
          }
          console.log(`[AddDetail] RegisterSerialNo Calculated: ${nextSerialNo} (Max: ${nextSerialNo - 1})`);
        } catch (error) {
          console.error("상세도면 리스트 조회 실패 (SerialNo 계산 중):", error);
          toast.error("Failed to calculate serial number");
          return;
        }

        // 파일 업로드 ID 생성
        const uploadId = uuidv4();

        // 상세도면 추가
        const result = await editDetailDwgReceipt({
          dwgList: [
            {
              Mode: "ADD",
              Status: "Standby",
              RegisterId: 0,
              ProjectNo: drawing.ProjectNo,
              Discipline: drawing.Discipline,
              DrawingKind: drawing.DrawingKind,
              DrawingNo: drawing.DrawingNo,
              DrawingName: drawing.DrawingName,
              RegisterGroupId: drawing.RegisterGroupId,
              RegisterSerialNo: nextSerialNo, // 자동 증가값 사용
              RegisterKind: registerKind,
              DrawingRevNo: drawingUsage === "CMT" ? null : revision,
              Category: "TS", // To SHI (벤더가 SHI에게 제출)
              Receiver: null,
              Manager: drawing.ManagerNo,
              RegisterDesc: comment,
              UploadId: uploadId,
              RegCompanyCode: vendorCode,
            },
          ],
          userId,
          userNm: userName,
          vendorCode,
          email: userEmail,
        });

        if (result > 0) {
          // 파일 업로드 처리 (상세도면 추가 후)
          if (files.length > 0) {
            toast.info(t("addDetailDialog.uploadingFiles", { count: files.length }));
            
            // 모든 파일 상태를 uploading으로 변경
            files.forEach((_, index) => {
              updateFileProgress(index, 0, "uploading");
            });

            const uploadResult = await uploadFilesWithProgress({
              uploadId,
              userId,
              files,
              callbacks: {
                onProgress: (fileIndex, progress) => {
                  updateFileProgress(fileIndex, progress, "uploading");
                },
                onFileComplete: (fileIndex) => {
                  updateFileProgress(fileIndex, 100, "completed");
                },
                onFileError: (fileIndex, error) => {
                  updateFileProgress(fileIndex, 0, "error", error);
                },
              },
            });
            
            if (uploadResult.success) {
              toast.success(t("addDetailDialog.addSuccessWithUpload", { count: uploadResult.uploadedCount }));
            } else {
              toast.warning(t("addDetailDialog.addSuccessPartialUpload", { error: uploadResult.error }));
            }
          } else {
            toast.success(t("addDetailDialog.addSuccess"));
          }
          
          // API 호출 성공 시 무조건 다이얼로그 닫기 (파일 업로드 성공 여부와 무관)
          resetForm();
          onComplete();
          onOpenChange(false);
        } else {
          toast.error(t("addDetailDialog.addError"));
        }
      } else if (mode === "edit" && detailDrawing) {
        // 상세도면 수정
        const result = await editDetailDwgReceipt({
          dwgList: [
            {
              Mode: "MOD",
              Status: detailDrawing.Status,
              RegisterId: detailDrawing.RegisterId,
              ProjectNo: detailDrawing.ProjectNo,
              Discipline: detailDrawing.Discipline,
              DrawingKind: detailDrawing.DrawingKind,
              DrawingNo: detailDrawing.DrawingNo,
              DrawingName: detailDrawing.DrawingName,
              RegisterGroupId: detailDrawing.RegisterGroupId,
              RegisterSerialNo: detailDrawing.RegisterSerialNo,
              RegisterKind: registerKind,
              DrawingRevNo: drawingUsage === "CMT" ? null : revision,
              Category: detailDrawing.Category,
              Receiver: detailDrawing.Receiver,
              Manager: detailDrawing.Manager,
              RegisterDesc: comment,
              UploadId: detailDrawing.UploadId,
              RegCompanyCode: detailDrawing.RegCompanyCode || vendorCode,
            },
          ],
          userId,
          userNm: userName,
          vendorCode,
          email: userEmail,
        });

        if (result > 0) {
          toast.success(t("editDetailDialog.editSuccess"));
          resetForm();
          onComplete();
          onOpenChange(false);
        } else {
          toast.error(t("editDetailDialog.editError"));
        }
      }
    } catch (error) {
      console.error("상세도면 처리 실패:", error);
      toast.error(mode === "add" ? t("addDetailDialog.addErrorMessage") : t("editDetailDialog.editErrorMessage"));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleCancel = () => {
    if (showConfirmation) {
      setShowConfirmation(false);
    } else {
      resetForm();
      onOpenChange(false);
    }
  };

  // 상세도면 삭제 핸들러
  const handleDelete = async () => {
    if (!detailDrawing) return;

    try {
      setIsDeleting(true);
      
      const result = await editDetailDwgReceipt({
        dwgList: [
          {
            Mode: "DEL",
            Status: detailDrawing.Status,
            RegisterId: detailDrawing.RegisterId,
            ProjectNo: detailDrawing.ProjectNo,
            Discipline: detailDrawing.Discipline,
            DrawingKind: detailDrawing.DrawingKind,
            DrawingNo: detailDrawing.DrawingNo,
            DrawingName: detailDrawing.DrawingName,
            RegisterGroupId: detailDrawing.RegisterGroupId,
            RegisterSerialNo: detailDrawing.RegisterSerialNo,
            RegisterKind: detailDrawing.RegisterKind, // 기존 값 유지
            DrawingRevNo: detailDrawing.DrawingRevNo, // 기존 값 유지
            Category: detailDrawing.Category,
            Receiver: detailDrawing.Receiver,
            Manager: detailDrawing.Manager,
            RegisterDesc: detailDrawing.RegisterDesc,
            UploadId: detailDrawing.UploadId,
            RegCompanyCode: detailDrawing.RegCompanyCode || vendorCode,
          },
        ],
        userId,
        userNm: userName,
        vendorCode,
        email: userEmail,
      });

      if (result > 0) {
        toast.success("Detail drawing deleted successfully");
        setShowDeleteConfirmation(false);
        resetForm();
        onComplete();
        onOpenChange(false);
      } else {
        toast.error("Failed to delete detail drawing");
      }
    } catch (error) {
      console.error("상세도면 삭제 실패:", error);
      toast.error("An error occurred while deleting");
    } finally {
      setIsDeleting(false);
    }
  };

  // DrawingUsage가 변경되면 RegisterKind 초기화
  const handleDrawingUsageChange = (value: string) => {
    setDrawingUsage(value);
    setRegisterKind("");
    setRevision("");
    setRevisionError("");
  };

  // 선택된 RegisterKind의 Revision Rule
  const revisionRule = registerKindOptions.find((opt) => opt.value === registerKind)?.revisionRule || "";

  // 버튼 활성화 조건
  const isFormValid = mode === "add"
    ? drawingUsage.trim() !== "" &&
      registerKind.trim() !== "" &&
      (drawingUsage === "CMT" || (revision.trim() !== "" && !revisionError)) &&
      files.length > 0
    : registerKind.trim() !== "" &&
      (drawingUsage === "CMT" || (revision.trim() !== "" && !revisionError));

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {showConfirmation 
              ? t("addDetailDialog.confirmTitle", "확인") 
              : (mode === "edit" ? t("editDetailDialog.title") : t("addDetailDialog.title"))
            }
          </DialogTitle>
        </DialogHeader>

        {showConfirmation ? (
          <div className="space-y-6">
            <Alert>
              <Info className="h-4 w-4" />
              <AlertDescription>
                {t("addDetailDialog.confirmMessage", "아래 내용으로 제출하시겠습니까?")}
              </AlertDescription>
            </Alert>

            <div className="grid grid-cols-2 gap-4 border rounded-lg p-4 bg-muted/20">
              <div className="space-y-1">
                <Label className="text-xs text-muted-foreground">{t("addDetailDialog.drawingUsageLabel")}</Label>
                <p className="text-sm font-medium">
                  {drawingUsageOptions.find(opt => opt.value === drawingUsage)?.label || drawingUsage}
                </p>
              </div>
              <div className="space-y-1">
                <Label className="text-xs text-muted-foreground">{t("addDetailDialog.registerKindLabel")}</Label>
                <p className="text-sm font-medium">
                  {registerKindOptions.find(opt => opt.value === registerKind)?.label || registerKind}
                </p>
              </div>
              {drawingUsage !== "CMT" && (
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">{t("addDetailDialog.revisionLabel")}</Label>
                  <p className="text-sm font-medium">{revision}</p>
                </div>
              )}
              <div className="space-y-1 col-span-2">
                <Label className="text-xs text-muted-foreground">{t("addDetailDialog.commentLabel")}</Label>
                <p className="text-sm">{comment || "-"}</p>
              </div>
            </div>

            {files.length > 0 && (
              <div className="space-y-2">
                <Label>{t("addDetailDialog.selectedFiles", { count: files.length })}</Label>
                <div className="max-h-60 overflow-y-auto space-y-2 border rounded-lg p-2">
                  {isSubmitting ? (
                    <FileUploadProgressList fileProgresses={fileProgresses} />
                  ) : (
                    files.map((file, index) => (
                      <div key={index} className="flex items-center gap-2 p-2 rounded bg-muted/50 text-sm">
                        <FileIcon className="h-4 w-4 text-muted-foreground shrink-0" />
                        <span className="truncate flex-1">{file.name}</span>
                        <span className="text-xs text-muted-foreground whitespace-nowrap">
                          {(file.size / 1024 / 1024).toFixed(2)} MB
                        </span>
                      </div>
                    ))
                  )}
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="space-y-6">
            {/* 도면 정보 표시 */}
            {mode === "add" && drawing && (
              <Alert>
                <Info className="h-4 w-4" />
                <AlertDescription>
                  <div className="font-medium">{drawing.DrawingNo}</div>
                  <div className="text-sm text-muted-foreground">{drawing.DrawingName}</div>
                </AlertDescription>
              </Alert>
            )}

            {mode === "edit" && detailDrawing && (
              <Alert>
                <Info className="h-4 w-4" />
                <AlertDescription>
                  <div className="font-medium">{detailDrawing.DrawingNo} - Rev. {detailDrawing.DrawingRevNo}</div>
                  <div className="text-sm text-muted-foreground">{detailDrawing.DrawingName}</div>
                </AlertDescription>
              </Alert>
            )}

            {/* 도면용도 선택 (Add 모드에서만 표시) */}
            {mode === "add" && (
              <div className="space-y-2">
                <Label>{t("addDetailDialog.drawingUsageLabel")}</Label>
                <Select value={drawingUsage} onValueChange={handleDrawingUsageChange}>
                  <SelectTrigger>
                    <SelectValue placeholder={t("addDetailDialog.drawingUsagePlaceholder")} />
                  </SelectTrigger>
                  <SelectContent>
                    {drawingUsageOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* 등록종류 선택 */}
            <div className="space-y-2">
              <Label>{t("addDetailDialog.registerKindLabel")}</Label>
              <Select
                value={registerKind}
                onValueChange={setRegisterKind}
                disabled={mode === "add" && !drawingUsage}
              >
                <SelectTrigger>
                  <SelectValue placeholder={t("addDetailDialog.registerKindPlaceholder")} />
                </SelectTrigger>
                <SelectContent>
                  {registerKindOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {revisionRule && (
                <p className="text-sm text-muted-foreground">
                  {t("addDetailDialog.revisionFormatPrefix")}{revisionRule}
                </p>
              )}
            </div>

            {/* Revision 입력 */}
            {drawingUsage !== "CMT" && (
              <div className="space-y-2">
                <Label>{t("addDetailDialog.revisionLabel")}</Label>
                <Input
                  value={revision}
                  onChange={(e) => handleRevisionChange(e.target.value)}
                  placeholder={t("addDetailDialog.revisionPlaceholder")}
                  disabled={!registerKind}
                  className={revisionError ? "border-red-500 focus-visible:ring-red-500" : ""}
                />
                {revisionError && (
                  <p className="text-sm text-red-500 flex items-center gap-1">
                    {revisionError}
                  </p>
                )}
                {!revisionError && revision && (
                  <p className="text-sm text-green-600 flex items-center gap-1">
                    {t("addDetailDialog.revisionValid")}
                  </p>
                )}
              </div>
            )}

            {/* Comment 입력 */}
            <div className="space-y-2">
              <Label>{t("addDetailDialog.commentLabel")}</Label>
              <Textarea
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                placeholder={t("addDetailDialog.commentPlaceholder")}
                rows={3}
                className="resize-none"
              />
              <p className="text-xs text-muted-foreground">
                {t("addDetailDialog.commentMaxLength")}
              </p>
            </div>

            {/* 파일 업로드 (Add 모드에서만 표시) */}
            {mode === "add" && (
              <div className="space-y-2">
                <Label>{t("addDetailDialog.attachmentLabel")}</Label>
              <div
                {...getRootProps()}
                className={`
                  border-2 border-dashed rounded-lg p-8 text-center cursor-pointer
                  transition-colors
                  ${isDragActive ? "border-primary bg-primary/5" : "border-muted-foreground/25"}
                  ${files.length > 0 ? "py-4" : ""}
                `}
              >
                <input {...getInputProps()} />
                {files.length === 0 ? (
                  <div className="space-y-2">
                    <Upload className="h-8 w-8 mx-auto text-muted-foreground" />
                    <div>
                      <p className="text-sm font-medium">
                        {t("addDetailDialog.dragDropText")}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {t("addDetailDialog.fileInfo")}
                      </p>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <p className="text-sm font-medium">
                      {t("addDetailDialog.filesSelected", { count: files.length })}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {t("addDetailDialog.addMoreFiles")}
                    </p>
                  </div>
                )}
              </div>

              {/* 선택된 파일 목록 */}
              {files.length > 0 && (
                <div className="space-y-2 mt-4">
                  {isSubmitting ? (
                    // 업로드 중: 진행도 표시
                    <FileUploadProgressList fileProgresses={fileProgresses} />
                  ) : (
                    // 대기 중: 삭제 버튼 표시
                    <>
                      <div className="flex items-center justify-between mb-2">
                        <h4 className="text-sm font-medium">
                          {t("addDetailDialog.selectedFiles", { count: files.length })}
                        </h4>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={clearFiles}
                        >
                          {t("addDetailDialog.removeAll")}
                        </Button>
                      </div>
                      <div className="max-h-60 overflow-y-auto space-y-2">
                        {files.map((file, index) => (
                          <div
                            key={index}
                            className="flex items-center gap-2 p-2 border rounded-lg bg-muted/50"
                          >
                            <FileIcon className="h-4 w-4 text-muted-foreground shrink-0" />
                            <div className="flex-1 min-w-0">
                              <p className="text-sm truncate">{file.name}</p>
                              <p className="text-xs text-muted-foreground">
                                {(file.size / 1024 / 1024).toFixed(2)} MB
                              </p>
                            </div>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => removeFile(index)}
                            >
                              <X className="h-4 w-4" />
                            </Button>
                          </div>
                        ))}
                      </div>
                    </>
                  )}
                </div>
              )}
              </div>
            )}
          </div>
        )}

        <DialogFooter className={mode === "edit" && !showConfirmation ? "sm:justify-between" : ""}>
          {mode === "edit" && !showConfirmation && (
            <Button
              type="button"
              variant="destructive"
              onClick={() => setShowDeleteConfirmation(true)}
              disabled={isSubmitting}
            >
              <Trash2 className="h-4 w-4 mr-2" />
              {t("editDetailDialog.deleteButton", "Delete")}
            </Button>
          )}
          <div className="flex gap-2 justify-end sm:w-auto w-full">
            <Button variant="outline" onClick={handleCancel} disabled={isSubmitting}>
              {showConfirmation ? t("addDetailDialog.backButton", "뒤로") : t("addDetailDialog.cancelButton")}
            </Button>
            <Button onClick={handleSubmit} disabled={isSubmitting || !isFormValid}>
              {isSubmitting 
                ? t("addDetailDialog.processingButton") 
                : showConfirmation
                  ? t("addDetailDialog.confirmSubmit", "제출")
                  : t("addDetailDialog.nextButton", "다음")
              }
            </Button>
          </div>
        </DialogFooter>

        {/* Delete Confirmation Dialog */}
        <AlertDialog open={showDeleteConfirmation} onOpenChange={setShowDeleteConfirmation}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Delete Detail Drawing</AlertDialogTitle>
              <AlertDialogDescription>
                Are you sure you want to delete this detail drawing? This action cannot be undone.
                {detailDrawing && (
                  <span className="block mt-2 font-medium text-foreground">
                    {detailDrawing.DrawingNo} (Rev. {detailDrawing.DrawingRevNo})
                  </span>
                )}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooterComponent>
              <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
              <AlertDialogAction 
                onClick={handleDelete} 
                disabled={isDeleting}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              >
                {isDeleting ? "Deleting..." : "Delete"}
              </AlertDialogAction>
            </AlertDialogFooterComponent>
          </AlertDialogContent>
        </AlertDialog>
      </DialogContent>
    </Dialog>
  );
}