summaryrefslogtreecommitdiff
path: root/components/pq-input/pq-input-tabs.tsx
blob: 1bc2fc3820d502a0fade13bf9eb044efb4074eea (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
"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { X, Save, CheckCircle2, AlertTriangle, ChevronsUpDown, Download } from "lucide-react"
import prettyBytes from "pretty-bytes"
import { useToast } from "@/hooks/use-toast"
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible"

// Form components
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"

// Custom Dropzone, FileList components
import {
  Dropzone,
  DropzoneDescription,
  DropzoneInput,
  DropzoneTitle,
  DropzoneUploadIcon,
  DropzoneZone,
} from "@/components/ui/dropzone"
import {
  FileList,
  FileListAction,
  FileListDescription,
  FileListHeader,
  FileListIcon,
  FileListInfo,
  FileListItem,
  FileListName,
} from "@/components/ui/file-list"

// Dialog components
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog"

// Additional UI

import { Badge } from "@/components/ui/badge"

// Server actions
import {
  uploadVendorFileAction,
  savePQAnswersAction,
  submitPQAction,
  ProjectPQ,
} from "@/lib/pq/service"
import { PQGroupData } from "@/lib/pq/service"

// ----------------------------------------------------------------------
// 1) Define client-side file shapes
// ----------------------------------------------------------------------
interface LocalFileState {
  fileObj: File
  uploaded: boolean
}

// ----------------------------------------------------------------------
// 2) Zod schema for the entire form
// ----------------------------------------------------------------------
const pqFormSchema = z.object({
  answers: z.array(
    z.object({
      criteriaId: z.number(),
      // Must have at least 1 char
      answer: z.string().min(1, "Answer is required"),

      // SHI 코멘트와 벤더 답변 필드 추가
      shiComment: z.string().optional(),
      vendorReply: z.string().optional(),

      // Existing, uploaded files
      uploadedFiles: z
        .array(
          z.object({
            fileName: z.string(),
            url: z.string(),
            size: z.number().optional(),
          })
        )
        .min(1, "At least one file attachment is required"),

      // Local (not-yet-uploaded) files
      newUploads: z.array(
        z.object({
          fileObj: z.any(),
          uploaded: z.boolean().default(false),
        })
      ),

      // track saved state
      saved: z.boolean().default(false),
    })
  ),
})

type PQFormValues = z.infer<typeof pqFormSchema>

// ----------------------------------------------------------------------
// 3) Main Component: PQInputTabs
// ----------------------------------------------------------------------
export function PQInputTabs({
  data,
  vendorId,
  projectId,
  projectData,
  isReadOnly = false,
  currentPQ, // 추가: 현재 PQ Submission 정보
}: {
  data: PQGroupData[]
  vendorId: number
  projectId?: number
  projectData?: ProjectPQ | null
  isReadOnly?: boolean
  currentPQ?: { // PQ Submission 정보
    id: number;
    status: string;
    type: string;
  } | null
}) {

  const [isSaving, setIsSaving] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const [allSaved, setAllSaved] = React.useState(false)
  const [showConfirmDialog, setShowConfirmDialog] = React.useState(false)

  const { toast } = useToast()

  const shouldDisableInput = isReadOnly;

  // ----------------------------------------------------------------------
  // A) Create initial form values
  //     Mark items as "saved" if they have existing answer or attachments
  // ----------------------------------------------------------------------
  function createInitialFormValues(): PQFormValues {
    const answers: PQFormValues["answers"] = []

    data.forEach((group) => {
      group.items.forEach((item) => {
        // Check if the server item is already "complete"
        const hasExistingAnswer = item.answer && item.answer.trim().length > 0
        const hasExistingAttachments = item.attachments && item.attachments.length > 0

        // If either is present, we consider it "saved" initially
        const isAlreadySaved = hasExistingAnswer || hasExistingAttachments

        answers.push({
          criteriaId: item.criteriaId,
          answer: item.answer || "",
          shiComment: item.shiComment || "",
          vendorReply: item.vendorReply || "",
          uploadedFiles: item.attachments.map((attach) => ({
            fileName: attach.fileName,
            url: attach.filePath,
            size: attach.fileSize,
          })),
          newUploads: [],
          saved: isAlreadySaved,
        })
      })
    })

    return { answers }
  }

  // ----------------------------------------------------------------------
  // B) Set up react-hook-form
  // ----------------------------------------------------------------------
  const form = useForm<PQFormValues>({
    resolver: zodResolver(pqFormSchema),
    defaultValues: createInitialFormValues(),
    mode: "onChange",
  })

  // ----------------------------------------------------------------------
  // C) Track if all items are saved => controls Submit PQ button
  // ----------------------------------------------------------------------
  React.useEffect(() => {
    const values = form.getValues()
    // We consider items "saved" if `saved===true` AND they have an answer or attachments
    const allItemsSaved = values.answers.every(
      (answer) => answer.saved && (answer.answer || answer.uploadedFiles.length > 0)
    )
    setAllSaved(allItemsSaved)
  }, [form.watch()])

  // Helper to find the array index by criteriaId
  const getAnswerIndex = (criteriaId: number): number => {
    return form.getValues().answers.findIndex((a) => a.criteriaId === criteriaId)
  }

  // ----------------------------------------------------------------------
  // D) Handling File Drops, Removal
  // ----------------------------------------------------------------------
  const handleDropAccepted = (criteriaId: number, files: File[]) => {
    const answerIndex = getAnswerIndex(criteriaId)
    if (answerIndex === -1) return

    // Convert each dropped file into a LocalFileState
    const newLocalFiles: LocalFileState[] = files.map((f) => ({
      fileObj: f,
      uploaded: false,
    }))

    const current = form.getValues(`answers.${answerIndex}.newUploads`)
    form.setValue(`answers.${answerIndex}.newUploads`, [...current, ...newLocalFiles], {
      shouldDirty: true,
    })

    // Mark unsaved
    form.setValue(`answers.${answerIndex}.saved`, false, { shouldDirty: true })
  }

  const handleDropRejected = () => {
    toast({
      title: "File upload rejected",
      description: "Please check file size and type.",
      variant: "destructive",
    })
  }

  const removeNewUpload = (answerIndex: number, fileIndex: number) => {
    const current = [...form.getValues(`answers.${answerIndex}.newUploads`)]
    current.splice(fileIndex, 1)
    form.setValue(`answers.${answerIndex}.newUploads`, current, { shouldDirty: true })

    form.setValue(`answers.${answerIndex}.saved`, false, { shouldDirty: true })
  }

  const removeUploadedFile = (answerIndex: number, fileIndex: number) => {
    const current = [...form.getValues(`answers.${answerIndex}.uploadedFiles`)]
    current.splice(fileIndex, 1)
    form.setValue(`answers.${answerIndex}.uploadedFiles`, current, { shouldDirty: true })

    form.setValue(`answers.${answerIndex}.saved`, false, { shouldDirty: true })
  }

  // ----------------------------------------------------------------------
  // E) Saving a Single Item
  // ----------------------------------------------------------------------
  const handleSaveItem = async (answerIndex: number) => {
    try {
      const answerData = form.getValues(`answers.${answerIndex}`)
      const criteriaId = answerData.criteriaId
      const item = data.flatMap(group => group.items).find(item => item.criteriaId === criteriaId)
      const inputFormat = item?.inputFormat || "TEXT"
      // Validation
      // 모든 항목은 필수로 처리 (isRequired 제거됨)
      {
        if (inputFormat === "FILE") {
          // 파일 업로드 항목의 경우 첨부 파일이 있어야 함
          const hasFiles = answerData.uploadedFiles.length > 0 || answerData.newUploads.length > 0
          if (!hasFiles) {
            toast({
              title: "필수 항목",
              description: "필수 항목입니다. 파일을 업로드해주세요.",
              variant: "destructive",
            })
            return
          }
        } else if (inputFormat === "TEXT_FILE") {
          // 텍스트+파일 항목의 경우 텍스트 답변과 파일이 모두 있어야 함
          const hasFiles = answerData.uploadedFiles.length > 0 || answerData.newUploads.length > 0
          if (!answerData.answer || !hasFiles) {
            toast({
              title: "필수 항목",
              description: "필수 항목입니다. 텍스트 답변과 파일을 모두 입력해주세요.",
              variant: "destructive",
            })
            return
          }
        } else if (!answerData.answer) {
          // 일반 텍스트 입력 항목의 경우 답변이 있어야 함
          toast({
            title: "필수 항목",
            description: "필수 항목입니다. 답변을 입력해주세요.",
            variant: "destructive",
          })
          return
        }
      }

      // 입력 형식별 유효성 검사
      if (answerData.answer) {
        switch (inputFormat) {
          case "EMAIL":
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
            if (!emailRegex.test(answerData.answer)) {
              toast({
                title: "이메일 형식 오류",
                description: "올바른 이메일 형식을 입력해주세요. (예: example@company.com)",
                variant: "destructive",
              })
              return
            }
            break
          case "PHONE":
            const phoneRegex = /^[\d-]+$/
            if (!phoneRegex.test(answerData.answer)) {
              toast({
                title: "전화번호 형식 오류",
                description: "올바른 전화번호 형식을 입력해주세요. (예: 02-1234-5678)",
                variant: "destructive",
              })
              return
            }
            break
          case "NUMBER":
            const numberRegex = /^-?\d*\.?\d*$/
            if (!numberRegex.test(answerData.answer)) {
              toast({
                title: "숫자 형식 오류",
                description: "숫자만 입력해주세요. (소수점, 음수 허용)",
                variant: "destructive",
              })
              return
            }
            break
          case "TEXT":
          case "TEXT_FILE":
          case "FILE":
            // 텍스트 입력과 파일 업로드는 추가 검증 없음
            break
          default:
            // 알 수 없는 입력 형식
            break
        }
      }

      // Upload new files (if any)
      if (answerData.newUploads.length > 0) {
        setIsSaving(true)

        for (const localFile of answerData.newUploads) {
          try {
            const uploadResult = await uploadVendorFileAction(localFile.fileObj)
            const currentUploaded = form.getValues(`answers.${answerIndex}.uploadedFiles`)
            currentUploaded.push({
              fileName: uploadResult.fileName,
              url: uploadResult.url,
              size: uploadResult.size,
            })
            form.setValue(`answers.${answerIndex}.uploadedFiles`, currentUploaded, {
              shouldDirty: true,
            })
          } catch (error) {
            console.error("File upload error:", error)
            toast({
              title: "Upload Error",
              description: "Failed to upload file",
              variant: "destructive",
            })
          }
        }

        // Clear newUploads
        form.setValue(`answers.${answerIndex}.newUploads`, [], { shouldDirty: true })
      }

      // Save to DB
      const updatedAnswer = form.getValues(`answers.${answerIndex}`)
      const saveResult = await savePQAnswersAction({
        vendorId,
        projectId, // 프로젝트 ID 전달
        answers: [
          {
            criteriaId: updatedAnswer.criteriaId,
            answer: updatedAnswer.answer,
            shiComment: updatedAnswer.shiComment,
            vendorReply: updatedAnswer.vendorReply,
            attachments: updatedAnswer.uploadedFiles.map((f) => ({
              fileName: f.fileName,
              url: f.url,
              size: f.size,
            })),
          },
        ],
      })

      if (saveResult.ok) {
        // Mark as saved
        form.setValue(`answers.${answerIndex}.saved`, true, { shouldDirty: false })
        toast({
          title: "Saved",
          description: "Item saved successfully",
        })
      }
    } catch (error) {
      console.error("Save error:", error)
      toast({
        title: "Save Error",
        description: "Failed to save item",
        variant: "destructive",
      })
    } finally {
      setIsSaving(false)
    }
  }

  // For convenience
  const answers = form.getValues().answers
  const dirtyFields = form.formState.dirtyFields.answers

  // Check if any item is dirty or has new uploads
  const isAnyItemDirty = answers.some((answer, i) => {
    const itemDirty = !!dirtyFields?.[i]
    const hasNewUploads = answer.newUploads.length > 0
    return itemDirty || hasNewUploads
  })

  // ----------------------------------------------------------------------
  // F) Save All Items
  // ----------------------------------------------------------------------
  const handleSaveAll = async () => {
    try {
      setIsSaving(true)
      const answers = form.getValues().answers

      // Only save items that are dirty or have new uploads
      for (let i = 0; i < answers.length; i++) {
        const itemDirty = !!dirtyFields?.[i]
        const hasNewUploads = answers[i].newUploads.length > 0
        if (!itemDirty && !hasNewUploads) continue

        await handleSaveItem(i)
      }

      toast({
        title: "All Saved",
        description: "All items saved successfully",
      })
    } catch (error) {
      console.error("Save all error:", error)
      toast({
        title: "Save Error",
        description: "Failed to save all items",
        variant: "destructive",
      })
    } finally {
      setIsSaving(false)
    }
  }

  // ----------------------------------------------------------------------
  // G) Submission with Confirmation Dialog
  // ----------------------------------------------------------------------
  const handleSubmitPQ = () => {
    if (!allSaved) {
      toast({
        title: "Cannot Submit",
        description: "Please save all items before submitting",
        variant: "destructive",
      })
      return
    }
    setShowConfirmDialog(true)
  }

  const handleConfirmSubmission = async () => {
    try {
      setIsSubmitting(true);
      setShowConfirmDialog(false);

      // pqSubmissionId가 있으면 포함하여 전달
      const result = await submitPQAction({
        vendorId,
        projectId,
        pqSubmissionId: currentPQ?.id, // 현재 PQ Submission ID 사용
      });

      if (result.ok) {
        toast({
          title: "PQ Submitted",
          description: "Your PQ information has been submitted successfully",
        });
        // 제출 후 PQ 목록 페이지로 리디렉션
        window.location.href = "/partners/pq";
      } else {
        toast({
          title: "Submit Error",
          description: result.error || "Failed to submit PQ",
          variant: "destructive",
        });
      }
    } catch (error) {
      console.error("Submit error:", error);
      toast({
        title: "Submit Error",
        description: "Failed to submit PQ information",
        variant: "destructive",
      });
    } finally {
      setIsSubmitting(false);
    }
  };
  // 프로젝트 정보 표시 섹션
  const renderProjectInfo = () => {
    if (!projectData) return null;

    return (
      <div className="mb-6 bg-muted p-4 rounded-md">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-lg font-semibold">프로젝트 정보</h3>
          <Badge variant={getStatusVariant(projectData.status)}>
            {getStatusLabel(projectData.status)}
          </Badge>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <p className="text-sm font-medium text-muted-foreground">프로젝트 코드</p>
            <p>{projectData.projectCode}</p>
          </div>
          <div>
            <p className="text-sm font-medium text-muted-foreground">프로젝트명</p>
            <p>{projectData.projectName}</p>
          </div>
          {projectData.submittedAt && (
            <div className="col-span-1 md:col-span-2">
              <p className="text-sm font-medium text-muted-foreground">제출일</p>
              <p>{formatDate(projectData.submittedAt)}</p>
            </div>
          )}
        </div>
      </div>
    );
  };

  // 상태 표시용 함수
  const getStatusLabel = (status: string) => {
    switch (status) {
      case "REQUESTED": return "요청됨";
      case "IN_PROGRESS": return "진행중";
      case "SUBMITTED": return "제출됨";
      case "APPROVED": return "승인됨";
      case "REJECTED": return "반려됨";
      default: return status;
    }
  };

  const getStatusVariant = (status: string) => {
    switch (status) {
      case "REQUESTED": return "secondary";
      case "IN_PROGRESS": return "default";
      case "SUBMITTED": return "outline";
      case "APPROVED": return "outline";
      case "REJECTED": return "destructive";
      default: return "secondary";
    }
  };

  // 날짜 형식화 함수
  const formatDate = (date: Date) => {
    if (!date) return "-";
    return new Date(date).toLocaleDateString("ko-KR", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  // ----------------------------------------------------------------------
  // H) Render
  // ----------------------------------------------------------------------
  return (
    <Form {...form}>
      <form>
        {/* 프로젝트 정보 섹션 */}
        {renderProjectInfo()}

        <Tabs defaultValue={data[0]?.groupName || ""} className="w-full">
          {/* Top Controls */}
          <div className="flex justify-between items-center mb-4">
            <TabsList className="grid grid-cols-4">
              {data.map((group) => (
                <TabsTrigger
                  key={group.groupName}
                  value={group.groupName}
                  className="truncate"
                >
                  <div className="flex items-center gap-2">
                    {/* Mobile: truncated version */}
                    <span className="block sm:hidden">
                      {group.groupName.length > 5
                        ? group.groupName.slice(0, 5) + "..."
                        : group.groupName}
                    </span>
                    {/* Desktop: full text */}
                    <span className="hidden sm:block">{group.groupName}</span>
                    <span className="inline-flex items-center justify-center h-5 min-w-5 px-1 rounded-full bg-muted text-xs font-medium">
                      {group.items.length}
                    </span>
                  </div>
                </TabsTrigger>
              ))}
            </TabsList>

            <div className="flex gap-2">
              {/* Save All button */}
              <Button
                type="button"
                variant="outline"
                disabled={isSaving || !isAnyItemDirty || shouldDisableInput}
                onClick={handleSaveAll}
              >
                {isSaving ? "Saving..." : "Save All"}
                <Save className="ml-2 h-4 w-4" />
              </Button>

              {/* Submit PQ button */}
              <Button
                type="button"
                disabled={!allSaved || isSubmitting || shouldDisableInput}
                onClick={handleSubmitPQ}
              >
                {isSubmitting ? "Submitting..." : "Submit PQ"}
                <CheckCircle2 className="ml-2 h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* Render each group */}
          {data.map((group) => (
            <TabsContent key={group.groupName} value={group.groupName}>
              {/* 2-column grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pb-4">
                {group.items.map((item) => {
                  const { criteriaId, code, checkPoint, description, contractInfo, additionalRequirement } = item
                  const answerIndex = getAnswerIndex(criteriaId)
                  if (answerIndex === -1) return null

                  const isSaved = form.watch(`answers.${answerIndex}.saved`)
                  const newUploads = form.watch(`answers.${answerIndex}.newUploads`)
                  const dirtyFieldsItem = form.formState.dirtyFields.answers?.[answerIndex]

                  const isItemDirty = !!dirtyFieldsItem
                  const hasNewUploads = newUploads.length > 0
                  const canSave = isItemDirty || hasNewUploads
            

                  return (
                    <Collapsible key={criteriaId} defaultOpen={!isSaved} className="w-full">
                      <Card className={isSaved ? "border-green-200" : ""}>
                        <CardHeader className="pb-1">
                          <div className="flex justify-between">
                            <div className="flex-1">
                              <div className="flex items-center gap-2">
                                <CollapsibleTrigger asChild>
                                  <Button variant="ghost" size="sm" className="p-0 h-7 w-7">
                                    <ChevronsUpDown className="h-4 w-4" />
                                    <span className="sr-only">Toggle</span>
                                  </Button>
                                </CollapsibleTrigger>
                                <CardTitle className="text-md">
                                  {code} - {checkPoint}

                                </CardTitle>
                              </div>
                              {description && (
                                <CardDescription className="mt-1 whitespace-pre-wrap">
                                  {description}
                                </CardDescription>
                              )}
                            </div>

                            {/* Save Status & Button */}
                            <div className="flex items-center gap-2">
                              {!isSaved && canSave && (
                                <span className="text-amber-600 text-xs flex items-center">
                                  <AlertTriangle className="h-4 w-4 mr-1" />
                                  Not Saved
                                </span>
                              )}
                              {isSaved && (
                                <span className="text-green-600 text-xs flex items-center">
                                  <CheckCircle2 className="h-4 w-4 mr-1" />
                                  Saved
                                </span>
                              )}

                              <Button
                                size="sm"
                                variant="outline"
                                disabled={isSaving || !canSave}
                                onClick={() => handleSaveItem(answerIndex)}
                              >
                                Save
                              </Button>
                            </div>
                          </div>
                        </CardHeader>

                        <CollapsibleContent>
                          <CardContent className="pt-3 space-y-3">
                            {/* 프로젝트별 추가 필드 (contractInfo, additionalRequirement) */}
                            {projectId && contractInfo && (
                              <div className="space-y-1">
                                <FormLabel className="text-sm font-medium">계약 정보</FormLabel>
                                <div className="rounded-md bg-muted/30 p-3 text-sm whitespace-pre-wrap">
                                  {contractInfo}
                                </div>
                              </div>
                            )}

                            {projectId && additionalRequirement && (
                              <div className="space-y-1">
                                <FormLabel className="text-sm font-medium">추가 요구사항</FormLabel>
                                <div className="rounded-md bg-muted/30 p-3 text-sm whitespace-pre-wrap">
                                  {additionalRequirement}
                                </div>
                              </div>
                            )}

                            {/* Answer Field - 입력 형식에 따라 다르게 렌더링 */}
                            {item.inputFormat !== "FILE" && (
                              <FormField
                                control={form.control}
                                name={`answers.${answerIndex}.answer`}
                                render={({ field }) => (
                                  <FormItem className="mt-2">
                                    <FormLabel>
                                      {(() => {
                                        const inputFormat = item.inputFormat || "TEXT";
                                        switch (inputFormat) {
                                          case "EMAIL":
                                            return "이메일 주소";
                                          case "PHONE":
                                            return "전화번호";
                                          case "NUMBER":
                                            return "숫자 값";
                                          case "TEXT_FILE":
                                            return "텍스트 답변";
                                          default:
                                            return "답변";
                                        }
                                      })()}
                                    </FormLabel>
                                    <FormControl>
                                      {(() => {
                                        const inputFormat = item.inputFormat || "TEXT";
                                        
                                        switch (inputFormat) {
                                          case "EMAIL":
                                            return (
                                              <Input
                                                {...field}
                                                type="email"
                                                disabled={shouldDisableInput}
                                                placeholder="example@company.com"
                                                onChange={(e) => {
                                                  field.onChange(e)
                                                  form.setValue(
                                                    `answers.${answerIndex}.saved`,
                                                    false,
                                                    { shouldDirty: true }
                                                  )
                                                }}
                                              />
                                            );
                                          case "PHONE":
                                            return (
                                              <Input
                                                {...field}
                                                type="tel"
                                                disabled={shouldDisableInput}
                                                placeholder="02-1234-5678"
                                                onChange={(e) => {
                                                  field.onChange(e)
                                                  form.setValue(
                                                    `answers.${answerIndex}.saved`,
                                                    false,
                                                    { shouldDirty: true }
                                                  )
                                                }}
                                              />
                                            );
                                          case "NUMBER":
                                            return (
                                              <Input
                                                {...field}
                                                type="text"
                                                disabled={shouldDisableInput}
                                                placeholder="숫자를 입력하세요"
                                                onChange={(e) => {
                                                  // 숫자만 허용
                                                  const value = e.target.value;
                                                  if (value === '' || /^-?\d*\.?\d*$/.test(value)) {
                                                    field.onChange(value)
                                                    form.setValue(
                                                      `answers.${answerIndex}.saved`,
                                                      false,
                                                      { shouldDirty: true }
                                                    )
                                                  }
                                                }}
                                              />
                                            );
                                          case "TEXT_FILE":
                                            return (
                                              <div className="space-y-2">
                                                <Textarea
                                                  {...field}
                                                  disabled={shouldDisableInput}
                                                  className="min-h-24"
                                                  placeholder="텍스트 답변을 입력하세요"
                                                  onChange={(e) => {
                                                    field.onChange(e)
                                                    form.setValue(
                                                      `answers.${answerIndex}.saved`,
                                                      false,
                                                      { shouldDirty: true }
                                                    )
                                                  }}
                                                />
                                                <div className="text-sm text-muted-foreground">
                                                  &quot;파일 업로드는 첨부 파일 섹션에서 진행해주세요.&quot;
                                                </div>
                                              </div>
                                            );
                                          default: // TEXT
                                            return (
                                              <Textarea
                                                {...field}
                                                disabled={shouldDisableInput}
                                                className="min-h-24"
                                                placeholder="답변을 입력해주세요."
                                                onChange={(e) => {
                                                  field.onChange(e)
                                                  form.setValue(
                                                    `answers.${answerIndex}.saved`,
                                                    false,
                                                    { shouldDirty: true }
                                                  )
                                                }}
                                              />
                                            );
                                        }
                                      })()}
                                    </FormControl>
                                    <FormMessage />
                                  </FormItem>
                                )}
                              />
                            )}

                            {/* FILE 형식일 때 안내 메시지 */}
                            {item.inputFormat === "FILE" && (
                              <div className="mt-2">
                                <FormLabel>파일 업로드</FormLabel>
                                <div className="text-sm text-muted-foreground">
                                  &quot;파일을 업로드해주세요.&quot;
                                </div>
                              </div>
                            )}

                            {/* Attachments / Dropzone - FILE 또는 TEXT_FILE 형식에서만 활성화 */}
                            {(item.inputFormat === "FILE" || item.inputFormat === "TEXT_FILE") && (
                              <div className="grid gap-2 mt-3">
                                <FormLabel>첨부 파일</FormLabel>
                              <Dropzone
                                maxSize={6e8} // 600MB
                                onDropAccepted={(files) =>
                                  handleDropAccepted(criteriaId, files)
                                }
                                onDropRejected={handleDropRejected}
                                disabled={shouldDisableInput}
                              >
                                {() => (
                                  <FormItem>
                                    <DropzoneZone className="flex justify-center h-24">
                                      <FormControl>
                                        <DropzoneInput />
                                      </FormControl>
                                      <div className="flex items-center gap-6">
                                        <DropzoneUploadIcon />
                                        <div className="grid gap-0.5">
                                          <DropzoneTitle>파일을 드래그하거나 클릭하여 업로드</DropzoneTitle>
                                          <DropzoneDescription>
                                            PDF, Word, Excel, 이미지 파일 (최대 600MB)
                                          </DropzoneDescription>
                                        </div>
                                      </div>
                                    </DropzoneZone>
                                    <FormDescription>
                                      또는 클릭하여 파일 선택
                                    </FormDescription>
                                    <FormMessage />
                                  </FormItem>
                                )}
                              </Dropzone>
                            </div>

                            )}

                            {/* Existing + Pending Files - FILE 또는 TEXT_FILE 형식에서만 활성화 */}
                            {(item.inputFormat === "FILE" || item.inputFormat === "TEXT_FILE") && (
                              <div className="mt-4 space-y-4">
                                {/* 1) Not-yet-uploaded files */}
                                {newUploads.length > 0 && (
                                  <div className="grid gap-2">
                                    <h6 className="text-sm font-medium">
                                      업로드 대기 중인 파일 ({newUploads.length})
                                    </h6>
                                    <FileList>
                                      {newUploads.map((f, fileIndex) => {
                                        const fileObj = f.fileObj
                                        if (!fileObj) return null

                                        return (
                                          <FileListItem key={fileIndex}>
                                            <FileListHeader>
                                              <FileListIcon />
                                              <FileListInfo>
                                                <FileListName>{fileObj.name}</FileListName>
                                                <FileListDescription>
                                                  {prettyBytes(fileObj.size)}
                                                </FileListDescription>
                                              </FileListInfo>
                                              <FileListAction
                                                onClick={() =>
                                                  removeNewUpload(answerIndex, fileIndex)
                                                }
                                              >
                                                <X className="h-4 w-4" />
                                                <span className="sr-only">Remove</span>
                                              </FileListAction>
                                            </FileListHeader>
                                          </FileListItem>
                                        )
                                      })}
                                    </FileList>
                                  </div>
                                )}

                                {/* 2) Already uploaded files */}
                                {form
                                  .watch(`answers.${answerIndex}.uploadedFiles`)
                                  .map((file, fileIndex) => (
                                    <FileListItem key={fileIndex}>
                                      <FileListHeader>
                                        <FileListIcon />
                                        <FileListInfo>
                                          <FileListName>{file.fileName}</FileListName>
                                          {/* If you want to display the path: 
                                              <FileListDescription>{file.url}</FileListDescription> 
                                          */}
                                        </FileListInfo>
                                        {file.size && (
                                          <span className="text-xs text-muted-foreground">
                                            {prettyBytes(file.size)}
                                          </span>
                                        )}
                                        <div className="flex gap-1">
                                          <FileListAction
                                            onClick={async () => {
                                              try {
                                                const { downloadFile } = await import('@/lib/file-download')
                                                await downloadFile(file.url, file.fileName, {
                                                  showToast: true,
                                                  onError: (error) => {
                                                    console.error('다운로드 오류:', error)
                                                    toast({
                                                      title: "다운로드 실패",
                                                      description: error,
                                                      variant: "destructive"
                                                    })
                                                  },
                                                  onSuccess: (fileName, fileSize) => {
                                                    console.log(`다운로드 성공: ${fileName} (${fileSize} bytes)`)
                                                  }
                                                })
                                              } catch (error) {
                                                console.error('다운로드 오류:', error)
                                                toast({
                                                  title: "다운로드 실패",
                                                  description: "파일 다운로드 중 오류가 발생했습니다.",
                                                  variant: "destructive"
                                                })
                                              }
                                            }}
                                          >
                                            <Download className="h-4 w-4" />
                                            <span className="sr-only">Download</span>
                                          </FileListAction>
                                          <FileListAction
                                            onClick={() =>
                                              removeUploadedFile(answerIndex, fileIndex)
                                            }
                                          >
                                            <X className="h-4 w-4" />
                                            <span className="sr-only">Remove</span>
                                          </FileListAction>
                                        </div>
                                      </FileListHeader>
                                    </FileListItem>
                                  ))}
                              </div>
                            )}

                            {/* SHI 코멘트 필드 (읽기 전용) */}
                            {item.shiComment && (
                              <FormField
                                control={form.control}
                                name={`answers.${answerIndex}.shiComment`}
                                render={({ field }) => (
                                  <FormItem className="mt-2">
                                    <FormLabel className="text-amber-600">SHI 코멘트</FormLabel>
                                    <FormControl>
                                      <Textarea
                                        {...field}
                                        disabled={true}
                                        className="min-h-20 bg-muted/50"
                                        placeholder="SHI 코멘트가 없습니다."
                                      />
                                    </FormControl>
                                    <FormMessage />
                                  </FormItem>
                                )}
                              />
                            )}

                            {/* Vendor Reply 필드 */}
                            <FormField
                              control={form.control}
                              name={`answers.${answerIndex}.vendorReply`}
                              render={({ field }) => (
                                <FormItem className="mt-2">
                                  <FormLabel className="text-blue-600">벤더 Reply</FormLabel>
                                  <FormControl>
                                    <Textarea
                                      {...field}
                                      disabled={shouldDisableInput}
                                      className="min-h-20 bg-muted/50"
                                      placeholder="벤더 Reply를 입력하세요."
                                      onChange={(e) => {
                                        field.onChange(e)
                                        form.setValue(
                                          `answers.${answerIndex}.saved`,
                                          false,
                                          { shouldDirty: true }
                                        )
                                      }}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />

                          </CardContent>
                        </CollapsibleContent>
                      </Card>
                    </Collapsible>
                  )
                })}
              </div>
            </TabsContent>
          ))}
        </Tabs>
      </form>

      {/* Confirmation Dialog */}
      <Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Confirm Submission</DialogTitle>
            <DialogDescription>
              {projectId
                ? `${projectData?.projectCode} 프로젝트의 PQ 응답을 제출하시겠습니까?`
                : "일반 PQ 응답을 제출하시겠습니까?"
              } 제출 후에는 수정이 불가능합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 max-h-[600px] overflow-y-auto ">
            {data.map((group) => (
              <Collapsible key={group.groupName} defaultOpen>
                <CollapsibleTrigger asChild>
                  <div className="flex justify-between items-center p-2 mb-1 cursor-pointer ">
                    <p className="font-semibold">{group.groupName}</p>
                    <ChevronsUpDown className="h-4 w-4 ml-2" />
                  </div>
                </CollapsibleTrigger>

                <CollapsibleContent>
                  {group.items.map((item) => {
                    const answerObj = form
                      .getValues()
                      .answers.find((a) => a.criteriaId === item.criteriaId)

                    if (!answerObj) return null

                    return (
                      <div key={item.criteriaId} className="mb-2 p-2 ml-2 border rounded-md text-sm">
                        {/* code & checkPoint */}
                        <p className="font-semibold">
                          {item.code} - {item.checkPoint}
                        </p>

                        {/* user's typed answer */}
                        <p className="text-sm font-medium mt-2">Answer:</p>
                        <p className="whitespace-pre-wrap text-sm">
                          {answerObj.answer || "(no answer)"}
                        </p>
                        {/* attachments */}
                        <p>Attachments:</p>
                        {answerObj.uploadedFiles.length > 0 ? (
                          <ul className="list-disc list-inside ml-4 text-xs">
                            {answerObj.uploadedFiles.map((file, idx) => (
                              <li key={idx}>{file.fileName}</li>
                            ))}
                          </ul>
                        ) : (
                          <p className="text-xs text-muted-foreground">(none)</p>
                        )}
                      </div>
                    )
                  })}
                </CollapsibleContent>
              </Collapsible>
            ))}
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowConfirmDialog(false)}
              disabled={isSubmitting}
            >
              Cancel
            </Button>
            <Button onClick={handleConfirmSubmission} disabled={isSubmitting}>
              {isSubmitting ? "Submitting..." : "Confirm Submit"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Form>
  )
}