summaryrefslogtreecommitdiff
path: root/lib/general-contracts/detail/general-contract-basic-info.tsx
blob: b0378912340acaa87934cfdc418d4912f5257e27 (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
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
'use client'

import React, { useState } from 'react'
import { useSession } from 'next-auth/react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import { Save, LoaderIcon } from 'lucide-react'
import { updateContractBasicInfo, getContractBasicInfo } from '../service'
import { toast } from 'sonner'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { GeneralContract } from '@/db/schema'
import { ContractDocuments } from './general-contract-documents'
import { getPaymentTermsForSelection, getIncotermsForSelection, getPlaceOfShippingForSelection, getPlaceOfDestinationForSelection } from '@/lib/procurement-select/service'
import { TAX_CONDITIONS, getTaxConditionName } from '@/lib/tax-conditions/types'
import { GENERAL_CONTRACT_SCOPES } from '@/lib/general-contracts/types'
import { uploadContractAttachment, getContractAttachments, deleteContractAttachment, getContractAttachmentForDownload } from '../service'
import { downloadFile } from '@/lib/file-download'
import { FileText, Upload, Download, Trash2 } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'

interface ContractBasicInfoProps {
  contractId: number
}

interface PaymentBeforeDelivery {
  apBond?: boolean
  apBondPercent?: string
  drawingSubmission?: boolean
  drawingSubmissionPercent?: string
  materialPurchase?: boolean
  materialPurchasePercent?: string
  additionalCondition?: boolean
  additionalConditionPercent?: string
}

interface PaymentAfterDelivery {
  commissioning?: boolean
  commissioningPercent?: string
  finalDocument?: boolean
  finalDocumentPercent?: string
  other?: boolean
  otherText?: string
}

export function ContractBasicInfo({ contractId }: ContractBasicInfoProps) {
  const session = useSession()
  const [isLoading, setIsLoading] = useState(false)
  const [contract, setContract] = useState<GeneralContract | null>(null)
  const userId = session.data?.user?.id ? Number(session.data.user.id) : null
  
  // 독립적인 상태 관리
  const [paymentDeliveryPercent, setPaymentDeliveryPercent] = useState('')

  // Procurement 데이터 상태들
  const [paymentTermsOptions, setPaymentTermsOptions] = useState<Array<{code: string, description: string}>>([])
  const [incotermsOptions, setIncotermsOptions] = useState<Array<{code: string, description: string}>>([])
  const [shippingPlaces, setShippingPlaces] = useState<Array<{code: string, description: string}>>([])
  const [destinationPlaces, setDestinationPlaces] = useState<Array<{code: string, description: string}>>([])
  const [procurementLoading, setProcurementLoading] = useState(false)
  
  const [formData, setFormData] = useState({
    contractScope: '', // 계약확정범위
    specificationType: '',
    specificationManualText: '',
    unitPriceType: '',
    warrantyPeriod: {
      납품후: { enabled: false, period: 0, maxPeriod: 0 },
      인도후: { enabled: false, period: 0, maxPeriod: 0 },
      작업후: { enabled: false, period: 0, maxPeriod: 0 },
      기타: { enabled: false, period: 0, maxPeriod: 0 },
    },
    contractAmount: null,
    currency: 'KRW',
    linkedPoNumber: '',
    linkedBidNumber: '',
    notes: '',
    // 개별 JSON 필드들 (스키마에 맞게)
    paymentBeforeDelivery: {} as PaymentBeforeDelivery,
    paymentDelivery: '', // varchar 타입
    paymentDeliveryAdditionalText: '',
    paymentAfterDelivery: {} as PaymentAfterDelivery,
    paymentTerm: '',
    taxType: '',
    liquidatedDamages: false,
    liquidatedDamagesPercent: '',
    deliveryType: '',
    deliveryTerm: '',
    shippingLocation: '',
    dischargeLocation: '',
    contractDeliveryDate: '',
    contractEstablishmentConditions: {
      regularVendorRegistration: false,
      projectAward: false,
      ownerApproval: false,
      other: false,
    },
    interlockingSystem: '',
    mandatoryDocuments: {
      technicalDataAgreement: false,
      nda: false,
      basicCompliance: false,
      safetyHealthAgreement: false,
    },
    contractTerminationConditions: {
      standardTermination: false,
      projectNotAwarded: false,
      other: false,
    },
    externalYardEntry: 'N', // 사외업체 야드투입 (Y/N)
    contractAmountReason: '', // 합의계약 미확정 사유
  })
  
  const [errors] = useState<Record<string, string>>({})
  const [specificationFiles, setSpecificationFiles] = useState<Array<{ id: number; fileName: string; filePath: string; uploadedAt: Date }>>([])
  const [isLoadingSpecFiles, setIsLoadingSpecFiles] = useState(false)
  const [showSpecFileDialog, setShowSpecFileDialog] = useState(false)
  const [unitPriceTypeOther, setUnitPriceTypeOther] = useState<string>('') // 단가 유형 '기타' 수기입력
  const [showYardEntryConfirmDialog, setShowYardEntryConfirmDialog] = useState(false)

  // 계약 데이터 로드
  React.useEffect(() => {
    const loadContract = async () => {
      try {
        console.log('Loading contract with ID:', contractId)
        const contractData = await getContractBasicInfo(contractId)
        console.log('Contract data received:', contractData)
        setContract(contractData as GeneralContract)
        
        // JSON 필드들 파싱 (null 체크) - 스키마에 맞게 개별 필드로 접근
        const paymentBeforeDelivery = (contractData?.paymentBeforeDelivery && typeof contractData.paymentBeforeDelivery === 'object') ? contractData.paymentBeforeDelivery as any : {}
        const paymentAfterDelivery = (contractData?.paymentAfterDelivery && typeof contractData.paymentAfterDelivery === 'object') ? contractData.paymentAfterDelivery as any : {}
        const warrantyPeriod = (contractData?.warrantyPeriod && typeof contractData.warrantyPeriod === 'object') ? contractData.warrantyPeriod as any : {}
        const contractEstablishmentConditions = (contractData?.contractEstablishmentConditions && typeof contractData.contractEstablishmentConditions === 'object') ? contractData.contractEstablishmentConditions as any : {}
        const mandatoryDocuments = (contractData?.mandatoryDocuments && typeof contractData.mandatoryDocuments === 'object') ? contractData.mandatoryDocuments as any : {}
        const contractTerminationConditions = (contractData?.contractTerminationConditions && typeof contractData.contractTerminationConditions === 'object') ? contractData.contractTerminationConditions as any : {}
        
        // paymentDelivery에서 퍼센트와 타입 분리
        const paymentDeliveryValue = contractData?.paymentDelivery || ''
        let paymentDeliveryType = ''
        let paymentDeliveryPercentValue = ''
        
        if (paymentDeliveryValue.includes('%')) {
          const match = paymentDeliveryValue.match(/(\d+)%\s*(.+)/)
          if (match) {
            paymentDeliveryPercentValue = match[1]
            paymentDeliveryType = match[2]
          }
        } else {
          paymentDeliveryType = paymentDeliveryValue
        }
        
        setPaymentDeliveryPercent(paymentDeliveryPercentValue)
        
        // 합의계약(AD, AW)인 경우 인도조건 기본값 설정
        const defaultDeliveryTerm = (contractData?.type === 'AD' || contractData?.type === 'AW') 
          ? '본 표준하도급 계약에 따름'
          : (contractData?.deliveryTerm || '')
        
        setFormData({
          contractScope: contractData?.contractScope || '',
          specificationType: contractData?.specificationType || '',
          specificationManualText: contractData?.specificationManualText || '',
          unitPriceType: contractData?.unitPriceType || '',
          warrantyPeriod: warrantyPeriod || {
            납품후: { enabled: false, period: 0, maxPeriod: 0 },
            인도후: { enabled: false, period: 0, maxPeriod: 0 },
            작업후: { enabled: false, period: 0, maxPeriod: 0 },
            기타: { enabled: false, period: 0, maxPeriod: 0 },
          },
          contractAmount: contractData?.contractAmount || null,
          currency: contractData?.currency || 'KRW',
          linkedPoNumber: contractData?.linkedPoNumber || '',
          linkedBidNumber: contractData?.linkedBidNumber || '',
          notes: contractData?.notes || '',
          // 개별 JSON 필드들
          paymentBeforeDelivery: paymentBeforeDelivery || {} as any,
          paymentDelivery: paymentDeliveryType, // 분리된 타입만 저장
          paymentAfterDelivery: paymentAfterDelivery || {} as any,
          paymentTerm: contractData?.paymentTerm || '',
          taxType: contractData?.taxType || '',
          liquidatedDamages: Boolean(contractData?.liquidatedDamages),
          liquidatedDamagesPercent: contractData?.liquidatedDamagesPercent || '',
          deliveryType: contractData?.deliveryType || '',
          deliveryTerm: defaultDeliveryTerm,
          shippingLocation: contractData?.shippingLocation || '',
          dischargeLocation: contractData?.dischargeLocation || '',
          contractDeliveryDate: contractData?.contractDeliveryDate || '',
          paymentDeliveryAdditionalText: (contractData as any)?.paymentDeliveryAdditionalText || '',
          contractEstablishmentConditions: contractEstablishmentConditions || {
            regularVendorRegistration: false,
            projectAward: false,
            ownerApproval: false,
            other: false,
          },
          interlockingSystem: contractData?.interlockingSystem || '',
          mandatoryDocuments: mandatoryDocuments || {
            technicalDataAgreement: false,
            nda: false,
            basicCompliance: false,
            safetyHealthAgreement: false,
          },
          contractTerminationConditions: contractTerminationConditions || {
            standardTermination: false,
            projectNotAwarded: false,
            other: false,
          },
          externalYardEntry: (contractData?.externalYardEntry as 'Y' | 'N') || 'N',
          contractAmountReason: (contractData as any)?.contractAmountReason || '',
        })
      } catch (error) {
        console.error('Error loading contract:', error)
        toast.error('계약 정보를 불러오는 중 오류가 발생했습니다.')
      }
    }
    
    if (contractId) {
      loadContract()
    }
  }, [contractId])

  // 사양 파일 목록 로드
  React.useEffect(() => {
    const loadSpecificationFiles = async () => {
      if (!contractId || formData.specificationType !== '첨부서류 참조') return
      
      setIsLoadingSpecFiles(true)
      try {
        const attachments = await getContractAttachments(contractId)
        const specFiles = (attachments as Array<{ id: number; fileName: string; filePath: string; documentName: string; uploadedAt: Date }>)
          .filter(att => att.documentName === '사양 및 공급범위' || att.documentName === 'specification')
          .map(att => ({
            id: att.id,
            fileName: att.fileName,
            filePath: att.filePath,
            uploadedAt: att.uploadedAt
          }))
        setSpecificationFiles(specFiles)
      } catch (error) {
        console.error('Error loading specification files:', error)
      } finally {
        setIsLoadingSpecFiles(false)
      }
    }
    
    loadSpecificationFiles()
  }, [contractId, formData.specificationType])

  // Procurement 데이터 로드 함수들
  const loadPaymentTerms = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPaymentTermsForSelection();
      setPaymentTermsOptions(data);
    } catch (error) {
      console.error("Failed to load payment terms:", error);
      toast.error("결제조건 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  const loadIncoterms = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getIncotermsForSelection();
      setIncotermsOptions(data);
    } catch (error) {
      console.error("Failed to load incoterms:", error);
      toast.error("운송조건 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  const loadShippingPlaces = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPlaceOfShippingForSelection();
      setShippingPlaces(data);
    } catch (error) {
      console.error("Failed to load shipping places:", error);
      toast.error("선적지 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  const loadDestinationPlaces = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPlaceOfDestinationForSelection();
      setDestinationPlaces(data);
    } catch (error) {
      console.error("Failed to load destination places:", error);
      toast.error("하역지 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  // 컴포넌트 마운트 시 procurement 데이터 로드
  React.useEffect(() => {
    loadPaymentTerms();
    loadIncoterms();
    loadShippingPlaces();
    loadDestinationPlaces();
  }, [loadPaymentTerms, loadIncoterms, loadShippingPlaces, loadDestinationPlaces]);
  const handleSaveContractInfo = async () => {
    if (!userId) {
      toast.error('사용자 정보를 찾을 수 없습니다.')
      return
    }
    try {
      setIsLoading(true)
      
      // 필수값 validation 체크
      const validationErrors: string[] = []
      if (!formData.contractScope) validationErrors.push('계약확정범위')
      if (!formData.specificationType) validationErrors.push('사양')
      // 첨부서류 참조 선택 시 사양 파일 필수 체크
      if (formData.specificationType === '첨부서류 참조' && specificationFiles.length === 0) {
        validationErrors.push('사양 파일')
      }
      // LO 계약인 경우 계약체결유효기간 필수값 체크
      if (contract?.type === 'LO' && !contract?.validityEndDate) {
        validationErrors.push('계약체결유효기간')
      }
      if (!formData.paymentDelivery) validationErrors.push('납품 지급조건')
      // 계약확정범위가 '단가' 또는 '물량(실적)'이 아닌 경우에만 계약통화 필수값 체크
      if (formData.contractScope !== '단가' && formData.contractScope !== '물량(실적)' && !formData.currency) {
        validationErrors.push('계약통화')
      }
      // if (!formData.paymentTerm) validationErrors.push('지불조건')
      if (!formData.taxType) validationErrors.push('세금조건')
      
      if (validationErrors.length > 0) {
        toast.error(`다음 필수 항목을 입력해주세요: ${validationErrors.join(', ')}`)
        return
      }
      
      // paymentDelivery와 paymentDeliveryPercent 합쳐서 저장
      const dataToSave = {
        ...formData,
        paymentDelivery: (formData.paymentDelivery === 'L/C' || formData.paymentDelivery === 'T/T') && paymentDeliveryPercent
          ? `${paymentDeliveryPercent}% ${formData.paymentDelivery}`
          : formData.paymentDelivery
      }
      
      await updateContractBasicInfo(contractId, dataToSave, userId as number)
      toast.success('계약 정보가 저장되었습니다.')
    } catch (error) {
      console.error('Error saving contract info:', error)
      toast.error('계약 정보 저장 중 오류가 발생했습니다.')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle>계약 기본 정보</CardTitle>
      </CardHeader>
      <CardContent>
        <Tabs defaultValue="basic" className="w-full">
          <TabsList className="grid w-full grid-cols-4 h-auto overflow-x-auto">
            <TabsTrigger value="basic" className="text-xs px-2 py-2 whitespace-nowrap">기본 정보</TabsTrigger>
            <TabsTrigger value="conditions" className="text-xs px-2 py-2 whitespace-nowrap">지급/인도 조건</TabsTrigger>
            <TabsTrigger value="additional" className="text-xs px-2 py-2 whitespace-nowrap">추가 조건</TabsTrigger>
            <TabsTrigger value="documents" className="text-xs px-2 py-2 whitespace-nowrap">계약첨부문서</TabsTrigger>
          </TabsList>

      {/* 기본 정보 탭 */}
      <TabsContent value="basic" className="space-y-6">
        <Card>
      {/* 계약확정범위 및 보증기간/단가유형 */}
        <CardHeader>
          <CardTitle>계약확정범위 및 보증기간/단가유형</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 계약확정범위 */}
          <div className="flex flex-col gap-2">
            <Label htmlFor="contractScope">계약확정범위 *</Label>
            <Select
              value={formData.contractScope}
              onValueChange={(value) => setFormData(prev => ({ ...prev, contractScope: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="계약확정범위 선택" />
              </SelectTrigger>
              <SelectContent>
                {GENERAL_CONTRACT_SCOPES.map((scope) => (
                  <SelectItem key={scope} value={scope}>
                    {scope}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          {/* 3그리드: 보증기간, 사양, 단가 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* 보증기간 */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="warrantyPeriod">품질/하자 보증기간</Label>
              <div className="space-y-3">
                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyAfterDelivery"
                    checked={formData.warrantyPeriod.납품후?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        납품후: { 
                          ...prev.warrantyPeriod.납품후, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyAfterDelivery" className="text-sm">납품 후</Label>
                </div>
                {formData.warrantyPeriod.납품후?.enabled && (
                  <div className="ml-6 flex items-center space-x-2">
                    <Input
                      type="number"
                      placeholder="보증기간"
                      value={formData.warrantyPeriod.납품후?.period || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          납품후: { 
                            ...prev.warrantyPeriod.납품후, 
                            period: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월, 최대</span>
                    <Input
                      type="number"
                      placeholder="최대"
                      value={formData.warrantyPeriod.납품후?.maxPeriod || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          납품후: { 
                            ...prev.warrantyPeriod.납품후, 
                            maxPeriod: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월</span>
                  </div>
                )}

                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyAfterHandover"
                    checked={formData.warrantyPeriod.인도후?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        인도후: { 
                          ...prev.warrantyPeriod.인도후, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyAfterHandover" className="text-sm">인도 후</Label>
                </div>
                {formData.warrantyPeriod.인도후?.enabled && (
                  <div className="ml-6 flex items-center space-x-2">
                    <Input
                      type="number"
                      placeholder="보증기간"
                      value={formData.warrantyPeriod.인도후?.period || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          인도후: { 
                            ...prev.warrantyPeriod.인도후, 
                            period: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월, 최대</span>
                    <Input
                      type="number"
                      placeholder="최대"
                      value={formData.warrantyPeriod.인도후?.maxPeriod || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          인도후: { 
                            ...prev.warrantyPeriod.인도후, 
                            maxPeriod: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월</span>
                  </div>
                )}

                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyAfterWork"
                    checked={formData.warrantyPeriod.작업후?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        작업후: { 
                          ...prev.warrantyPeriod.작업후, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyAfterWork" className="text-sm">작업 후</Label>
                </div>
                {formData.warrantyPeriod.작업후?.enabled && (
                  <div className="ml-6 flex items-center space-x-2">
                    <Input
                      type="number"
                      placeholder="보증기간"
                      value={formData.warrantyPeriod.작업후?.period || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          작업후: { 
                            ...prev.warrantyPeriod.작업후, 
                            period: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월, 최대</span>
                    <Input
                      type="number"
                      placeholder="최대"
                      value={formData.warrantyPeriod.작업후?.maxPeriod || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          작업후: { 
                            ...prev.warrantyPeriod.작업후, 
                            maxPeriod: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월</span>
                  </div>
                )}

                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyOther"
                    checked={formData.warrantyPeriod.기타?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        기타: { 
                          ...prev.warrantyPeriod.기타, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyOther" className="text-sm">기타/미적용</Label>
                </div>
              </div>
            </div>
            {/* 사양 */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="specificationType">사양 <span className="text-red-600">*</span></Label>
              <Select value={formData.specificationType} onValueChange={(value) => setFormData(prev => ({ ...prev, specificationType: value }))}>
                <SelectTrigger className={errors.specificationType ? 'border-red-500' : ''}>
                  <SelectValue placeholder="사양을 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="첨부서류 참조">첨부서류 참조</SelectItem>
                  <SelectItem value="표준사양">표준사양</SelectItem>
                  <SelectItem value="수기사양">수기사양</SelectItem>
                </SelectContent>
              </Select>
                {errors.specificationType && (
                  <p className="text-sm text-red-600">사양은 필수값입니다.</p>
                )}
            </div>
            {/* 단가 */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="unitPriceType">
                단가 유형
                {(() => {
                  const contractType = contract?.type as string || ''
                  const contractCategory = contract?.category as string || ''
                  const unitPriceContractTypes = ['UP', 'LE', 'IL', 'AL', 'OS', 'OW']
                  const isUnitPriceRequired = contractCategory === 'unit_price' && unitPriceContractTypes.includes(contractType)
                  return isUnitPriceRequired ? <span className="text-red-600 ml-1">*</span> : null
                })()}
              </Label>
              <Select value={formData.unitPriceType} onValueChange={(value) => setFormData(prev => ({ ...prev, unitPriceType: value }))}>
                <SelectTrigger className={
                  (() => {
                    const contractType = contract?.type as string || ''
                    const contractCategory = contract?.category as string || ''
                    const unitPriceContractTypes = ['UP', 'LE', 'IL', 'AL', 'OS', 'OW']
                    const isUnitPriceRequired = contractCategory === 'unit_price' && unitPriceContractTypes.includes(contractType)
                    return isUnitPriceRequired && !formData.unitPriceType ? 'border-red-500' : ''
                  })()
                }>
                  <SelectValue placeholder="단가 유형을 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="자재개별단가">자재개별단가</SelectItem>
                  <SelectItem value="서비스용역단가">서비스용역단가</SelectItem>
                  <SelectItem value="프로젝트단가">프로젝트단가</SelectItem>
                  <SelectItem value="지역별단가">지역별단가</SelectItem>
                  <SelectItem value="직무직급단가">직무직급단가</SelectItem>
                  <SelectItem value="단계별단가">단계별단가</SelectItem>
                  <SelectItem value="기타">기타</SelectItem>
                </SelectContent>
              </Select>
              {/* 단가 유형 '기타' 선택 시 수기입력 필드 */}
              {formData.unitPriceType === '기타' && (
                <div className="mt-2">
                  <Input
                    value={unitPriceTypeOther}
                    onChange={(e) => setUnitPriceTypeOther(e.target.value)}
                    placeholder="단가 유형을 수기로 입력하세요"
                    className="mt-2"
                    required
                  />
                </div>
              )}
              {(() => {
                const contractType = contract?.type as string || ''
                const contractCategory = contract?.category as string || ''
                const unitPriceContractTypes = ['UP', 'LE', 'IL', 'AL', 'OS', 'OW']
                const isUnitPriceRequired = contractCategory === 'unit_price' && unitPriceContractTypes.includes(contractType)
                return isUnitPriceRequired && !formData.unitPriceType ? (
                  <p className="text-sm text-red-600">단가 유형은 필수값입니다.</p>
                ) : formData.unitPriceType === '기타' && !unitPriceTypeOther.trim() ? (
                  <p className="text-sm text-red-600">단가 유형(기타)을 입력해주세요.</p>
                ) : null
              })()}
            </div>
            {/* 선택에 따른 폼: vertical로 출력 */}
        

          {/* 사양이 수기사양일 때 매뉴얼 텍스트 */}
          {formData.specificationType === '수기사양' && (
            <div className="flex flex-col gap-2">
              <Label htmlFor="specificationManualText">사양 매뉴얼 텍스트</Label>
              <Textarea
                value={formData.specificationManualText}
                onChange={(e) => setFormData(prev => ({ ...prev, specificationManualText: e.target.value }))}
                placeholder="사양 매뉴얼 텍스트를 입력하세요"
                rows={3}
              />
            </div>
          )}

          {/* 사양이 첨부서류 참조일 때 파일 업로드 */}
          {formData.specificationType === '첨부서류 참조' && (
            <div className="flex flex-col gap-2">
              <div className="flex items-center justify-between">
                <Label htmlFor="specificationFile">
                  사양 파일 <span className="text-red-600">*</span>
                </Label>
                <Dialog open={showSpecFileDialog} onOpenChange={setShowSpecFileDialog}>
                  <DialogTrigger asChild>
                    <Button variant="outline" size="sm" type="button">
                      <Upload className="h-4 w-4 mr-2" />
                      파일 업로드
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="max-w-2xl">
                    <DialogHeader>
                      <DialogTitle>사양 파일 업로드</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      <div>
                        <Label htmlFor="file-upload">파일 선택</Label>
                        <Input
                          id="file-upload"
                          type="file"
                          onChange={async (e) => {
                            const file = e.target.files?.[0]
                            if (!file || !userId) return
                            
                            try {
                              setIsLoadingSpecFiles(true)
                              const result = await uploadContractAttachment(
                                contractId,
                                file,
                                userId.toString(),
                                '사양 및 공급범위'
                              )
                              
                              if (result.success) {
                                toast.success('사양 파일이 업로드되었습니다.')
                                // 파일 목록 새로고침
                                const attachments = await getContractAttachments(contractId)
                                const specFiles = (attachments as Array<{ id: number; fileName: string; filePath: string; documentName: string; uploadedAt: Date }>)
                                  .filter(att => att.documentName === '사양 및 공급범위' || att.documentName === 'specification')
                                  .map(att => ({
                                    id: att.id,
                                    fileName: att.fileName,
                                    filePath: att.filePath,
                                    uploadedAt: att.uploadedAt
                                  }))
                                setSpecificationFiles(specFiles)
                                setShowSpecFileDialog(false)
                                e.target.value = ''
                              } else {
                                toast.error(result.error || '파일 업로드에 실패했습니다.')
                              }
                            } catch (error) {
                              console.error('Error uploading file:', error)
                              toast.error('파일 업로드 중 오류가 발생했습니다.')
                            } finally {
                              setIsLoadingSpecFiles(false)
                            }
                          }}
                          disabled={isLoadingSpecFiles}
                        />
                      </div>
                      
                      {/* 업로드된 파일 목록 */}
                      {specificationFiles.length > 0 && (
                        <div className="space-y-2">
                          <Label>업로드된 파일</Label>
                          <div className="space-y-2 max-h-60 overflow-y-auto">
                            {specificationFiles.map((file) => (
                              <div key={file.id} className="flex items-center justify-between p-2 border rounded">
                                <div className="flex items-center gap-2">
                                  <FileText className="h-4 w-4 text-muted-foreground" />
                                  <span className="text-sm">{file.fileName}</span>
                                  <span className="text-xs text-muted-foreground">
                                    ({new Date(file.uploadedAt).toLocaleDateString()})
                                  </span>
                                </div>
                                <div className="flex items-center gap-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={async () => {
                                      try {
                                        const fileData = await getContractAttachmentForDownload(file.id, contractId)
                                        downloadFile(fileData.attachment?.filePath || '', fileData.attachment?.fileName || '', {
                                          showToast: true
                                        })
                                      } catch (error) {
                                        console.error('Error downloading file:', error)
                                        toast.error('파일 다운로드 중 오류가 발생했습니다.')
                                      }
                                    }}
                                  >
                                    <Download className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={async () => {
                                      try {
                                        await deleteContractAttachment(file.id, contractId)
                                        toast.success('파일이 삭제되었습니다.')
                                        setSpecificationFiles(prev => prev.filter(f => f.id !== file.id))
                                      } catch (error) {
                                        console.error('Error deleting file:', error)
                                        toast.error('파일 삭제 중 오류가 발생했습니다.')
                                      }
                                    }}
                                    className="text-red-600 hover:text-red-700"
                                  >
                                    <Trash2 className="h-4 w-4" />
                                  </Button>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  </DialogContent>
                </Dialog>
              </div>
              
              {specificationFiles.length === 0 && (
                <p className="text-sm text-red-600">사양 파일을 업로드해주세요.</p>
              )}
              
              {specificationFiles.length > 0 && (
                <div className="space-y-2">
                  {specificationFiles.map((file) => (
                    <div key={file.id} className="flex items-center justify-between p-2 border rounded text-sm">
                      <div className="flex items-center gap-2">
                        <FileText className="h-4 w-4 text-muted-foreground" />
                        <span>{file.fileName}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={async () => {
                            try {
                              const fileData = await getContractAttachmentForDownload(file.id, contractId)
                              downloadFile(fileData.attachment?.filePath || '', fileData.attachment?.fileName || '', {
                                showToast: true
                              })
                            } catch (error) {
                              console.error('Error downloading file:', error)
                              toast.error('파일 다운로드 중 오류가 발생했습니다.')
                            }
                          }}
                        >
                          <Download className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={async () => {
                            try {
                              await deleteContractAttachment(file.id, contractId)
                              toast.success('파일이 삭제되었습니다.')
                              setSpecificationFiles(prev => prev.filter(f => f.id !== file.id))
                            } catch (error) {
                              console.error('Error deleting file:', error)
                              toast.error('파일 삭제 중 오류가 발생했습니다.')
                            }
                          }}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          </div>

          
        </CardContent>
      </Card>
      </TabsContent>

      {/* 지급/인도 조건 탭 */}
      <TabsContent value="conditions" className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Payment & Delivery Conditions (지급/인도 조건)</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid grid-cols-6 gap-4">
              {/* 납품 전 지급조건 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">납품 전</Label>
                <div className="space-y-2">
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="apBond"
                      checked={formData.paymentBeforeDelivery.apBond || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          apBond: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="apBond" className="text-xs">AP Bond</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.apBondPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          apBondPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.apBond}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="drawingSubmission"
                      checked={formData.paymentBeforeDelivery.drawingSubmission || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          drawingSubmission: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="drawingSubmission" className="text-xs">도면제출</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.drawingSubmissionPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          drawingSubmissionPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.drawingSubmission}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="materialPurchase"
                      checked={formData.paymentBeforeDelivery.materialPurchase || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          materialPurchase: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="materialPurchase" className="text-xs">소재구매</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.materialPurchasePercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          materialPurchasePercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.materialPurchase}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                      id="additionalConditionBefore"
                      checked={formData.paymentBeforeDelivery.additionalCondition || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          additionalCondition: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="additionalConditionBefore" className="text-xs">추가조건</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.additionalConditionPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          additionalConditionPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.additionalCondition}
                    />
                  </div>
                </div>
              </div>

              {/* 납품 지급조건 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">납품</Label>
                <div className="space-y-2">
                  <div className="space-y-1">
                    <Label htmlFor="paymentDelivery" className="text-xs">지급조건 *</Label>
                    <Select value={formData.paymentDelivery} onValueChange={(value) => setFormData(prev => ({ ...prev, paymentDelivery: value }))}>
                      <SelectTrigger className={`h-8 text-xs ${errors.paymentDelivery ? 'border-red-500' : ''}`}>
                        <SelectValue placeholder="선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {paymentTermsOptions.map((term) => (
                          <SelectItem key={term.code} value={term.code} className="text-xs">
                            {term.code}
                          </SelectItem>
                        ))}
                        <SelectItem value="납품완료일로부터 60일 이내 지급" className="text-xs">60일 이내</SelectItem>
                        <SelectItem value="추가조건" className="text-xs">추가조건</SelectItem>
                      </SelectContent>
                    </Select>
                    {formData.paymentDelivery === '추가조건' && (
                      <Input
                        type="text"
                        value={formData.paymentDeliveryAdditionalText || ''}
                        onChange={(e) => setFormData(prev => ({ ...prev, paymentDeliveryAdditionalText: e.target.value }))}
                        placeholder="추가조건"
                        className="h-6 text-xs mt-1"
                      />
                    )}
                  </div>
                </div>
              </div>

              {/* 납품 외 지급조건 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">납품 외</Label>
                <div className="space-y-2">
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="commissioning"
                      checked={formData.paymentAfterDelivery.commissioning || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          commissioning: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="commissioning" className="text-xs">Commissioning</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentAfterDelivery.commissioningPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          commissioningPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentAfterDelivery.commissioning}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="finalDocument"
                      checked={formData.paymentAfterDelivery.finalDocument || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          finalDocument: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="finalDocument" className="text-xs">최종문서</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentAfterDelivery.finalDocumentPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          finalDocumentPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentAfterDelivery.finalDocument}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                      id="other"
                      checked={formData.paymentAfterDelivery.other || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          other: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="other" className="text-xs">기타</Label>
                    <Input
                      type="text"
                      placeholder="기타"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentAfterDelivery.otherText || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          otherText: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentAfterDelivery.other}
                    />
                  </div>
                </div>
              </div>

              {/* 지불조건 -> 세금조건 (지불조건 삭제됨) */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">세금조건</Label>
                <div className="space-y-2">
                  {/* 지불조건 필드 삭제됨
                  <div className="space-y-1">
                    <Label htmlFor="paymentTerm" className="text-xs">지불조건 *</Label>
                    <Select
                      value={formData.paymentTerm}
                      onValueChange={(value) => setFormData(prev => ({ ...prev, paymentTerm: value }))}
                    >
                      <SelectTrigger className={`h-8 text-xs ${errors.paymentTerm ? 'border-red-500' : ''}`}>
                        <SelectValue placeholder="선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {paymentTermsOptions.length > 0 ? (
                          paymentTermsOptions.map((option) => (
                            <SelectItem key={option.code} value={option.code} className="text-xs">
                              {option.code}
                            </SelectItem>
                          ))
                        ) : (
                          <SelectItem value="loading" disabled className="text-xs">
                            로딩중...
                          </SelectItem>
                        )}
                      </SelectContent>
                    </Select>
                  </div>
                  */}
                  <div className="space-y-1">
                    <Label htmlFor="taxType" className="text-xs">세금조건 *</Label>
                    <Select
                      value={formData.taxType}
                      onValueChange={(value) => setFormData(prev => ({ ...prev, taxType: value }))}
                    >
                      <SelectTrigger className={`h-8 text-xs ${errors.taxType ? 'border-red-500' : ''}`}>
                        <SelectValue placeholder="선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {TAX_CONDITIONS.map((condition) => (
                          <SelectItem key={condition.code} value={condition.code} className="text-xs">
                            {condition.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>

              {/* 클레임금액 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">클레임금액</Label>
                <div className="space-y-2">
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="liquidatedDamages"
                      checked={formData.liquidatedDamages || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        liquidatedDamages: e.target.checked
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <div className="flex flex-col">
                      <Label htmlFor="liquidatedDamages" className="text-xs">지체상금 (최대 징수 가능 비율)</Label>
                      <span className="text-[10px] text-muted-foreground">
                        * 일반적인 계약조건: 지체일수당 계약금액의 0.3%, 최대치 10%
                      </span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Input
                        type="number"
                        min="0"
                        placeholder=""
                        className="w-16 h-6 text-xs text-right"
                        value={formData.liquidatedDamagesPercent || ''}
                        onChange={(e) => setFormData(prev => ({
                          ...prev,
                          liquidatedDamagesPercent: e.target.value
                        }))}
                        disabled={!formData.liquidatedDamages}
                      />
                      <span className="text-xs">%</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 인도조건 섹션 */}
            <div className="mt-6">
              <h3 className="text-base font-semibold mb-3">인도조건</h3>
              <div className="grid grid-cols-6 gap-4">
                {/* 납기종류 */}
                <div className="space-y-2">
                  <Label htmlFor="deliveryType" className="text-xs">납기종류</Label>
                  <Select value={formData.deliveryType} onValueChange={(value) => setFormData(prev => ({ ...prev, deliveryType: value }))}>
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="단일납기" className="text-xs">단일납기</SelectItem>
                      <SelectItem value="분할납기" className="text-xs">분할납기</SelectItem>
                      <SelectItem value="구간납기" className="text-xs">구간납기</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 인도조건 */}
                <div className="space-y-2">
                  <Label htmlFor="deliveryTerm" className="text-xs">인도조건</Label>
                  <Select
                    value={formData.deliveryTerm}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, deliveryTerm: value }))}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {incotermsOptions.length > 0 ? (
                        incotermsOptions.map((option) => (
                          <SelectItem key={option.code} value={option.code} className="text-xs">
                            {option.code}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="loading" disabled className="text-xs">
                          로딩중...
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {/* 선적지 */}
                <div className="space-y-2">
                  <Label htmlFor="shippingLocation" className="text-xs">선적지</Label>
                  <Select
                    value={formData.shippingLocation}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, shippingLocation: value }))}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {shippingPlaces.length > 0 ? (
                        shippingPlaces.map((place) => (
                          <SelectItem key={place.code} value={place.code} className="text-xs">
                            {place.code}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="loading" disabled className="text-xs">
                          로딩중...
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {/* 하역지 */}
                <div className="space-y-2">
                  <Label htmlFor="dischargeLocation" className="text-xs">하역지</Label>
                  <Select
                    value={formData.dischargeLocation}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, dischargeLocation: value }))}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {destinationPlaces.length > 0 ? (
                        destinationPlaces.map((place) => (
                          <SelectItem key={place.code} value={place.code} className="text-xs">
                            {place.code}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="loading" disabled className="text-xs">
                          로딩중...
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {/* 계약납기일 */}
                <div className="space-y-2">
                  <Label htmlFor="contractDeliveryDate" className="text-xs">계약납기일</Label>
                  <Input
                    type="date"
                    value={formData.contractDeliveryDate}
                    onChange={(e) => setFormData(prev => ({ ...prev, contractDeliveryDate: e.target.value }))}
                    className="h-8 text-xs"
                  />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </TabsContent>

      {/* 추가 조건 탭 */}
      <TabsContent value="additional" className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Additional Conditions (추가조건)</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="contractAmount">계약금액 (자동계산)</Label>
                {(contract?.type === 'AD' || contract?.type === 'AW') || formData.contractScope === '단가' || formData.contractScope === '물량(실적)' ? (
                  <div className="space-y-2">
                    <Input
                      type="text"
                      value="미확정"
                      readOnly
                      className="bg-gray-50"
                    />
                    <div className="flex flex-col gap-2">
                      <Label htmlFor="contractAmountReason">미확정 사유</Label>
                      <Textarea
                        id="contractAmountReason"
                        value={formData.contractAmountReason}
                        onChange={(e) => setFormData(prev => ({ ...prev, contractAmountReason: e.target.value }))}
                        placeholder="계약금액 미확정 사유를 입력하세요"
                        rows={3}
                      />
                    </div>
                  </div>
                ) : (
                  <Input
                    type="text"
                    value={contract?.contractAmount ? new Intl.NumberFormat('ko-KR').format(Number(contract.contractAmount)) : '품목정보 없음'}
                    readOnly
                    className="bg-gray-50"
                    placeholder="품목정보에서 자동 계산됩니다"
                  />
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="currency">
                  계약통화
                  {formData.contractScope !== '단가' && formData.contractScope !== '물량(실적)' && <span className="text-red-600">*</span>}
                </Label>
                <Input
                  type="text"
                  value={formData.currency}
                  onChange={(e) => setFormData(prev => ({ ...prev, currency: e.target.value }))}
                  placeholder="계약통화를 입력하세요"
                  className={`${errors.currency ? 'border-red-500' : ''} ${formData.contractScope === '단가' || formData.contractScope === '물량(실적)' ? 'bg-gray-50' : ''}`}
                  disabled={formData.contractScope === '단가' || formData.contractScope === '물량(실적)'}
                />
                {errors.currency && formData.contractScope !== '단가' && formData.contractScope !== '물량(실적)' && (
                  <p className="text-sm text-red-600">계약통화는 필수값입니다.</p>
                )}
              </div>

              {/* 사외업체 야드투입 */}
              <div className="space-y-4 grid grid-cols-2 col-span-2">
                                                {/* 연동제적용 */}
                                                <div className="space-y-4 flex-1">
                  <Label className="text-base font-medium">연동제적용</Label>
                  <div className="space-y-2">
                    <Select value={formData.interlockingSystem} onValueChange={(value) => setFormData(prev => ({ ...prev, interlockingSystem: value }))}>
                      <SelectTrigger>
                        <SelectValue placeholder="연동제적용을 선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Y</SelectItem>
                        <SelectItem value="N">N</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <div className="flex items-center space-x-4">
                  <div className="space-y-4 flex-1">
                <Label className="text-base font-medium">사외업체 야드투입</Label>
                  <div className="flex items-center space-x-2">
                    <input
                      type="radio"
                      id="yardEntryYes"
                      name="externalYardEntry"
                      value="Y"
                      checked={formData.externalYardEntry === 'Y'}
                      onChange={(e) => setFormData(prev => ({ ...prev, externalYardEntry: 'Y' as 'Y' | 'N' }))}
                      className="rounded"
                    />
                    <Label htmlFor="yardEntryYes">Y</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="radio"
                      id="yardEntryNo"
                      name="externalYardEntry"
                      value="N"
                      checked={formData.externalYardEntry === 'N'}
                      onChange={(e) => {
                        // 이전 값이 'Y'였고 'N'으로 변경하는 경우 팝업 표시
                        if (formData.externalYardEntry === 'Y') {
                          setShowYardEntryConfirmDialog(true)
                        } else {
                          setFormData(prev => ({ ...prev, externalYardEntry: 'N' as 'Y' | 'N' }))
                        }
                      }}
                      className="rounded"
                    />
                    <Label htmlFor="yardEntryNo">N</Label>
                  </div>
                </div>
                {/* 사외업체 야드투입 'N' 선택 시 확인 팝업 */}
                <Dialog open={showYardEntryConfirmDialog} onOpenChange={setShowYardEntryConfirmDialog}>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>안전필수사항 확인</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      <p className="text-sm text-muted-foreground">
                        안전필수사항으로 사내작업여부를 재확인 바랍니다.
                      </p>
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="outline"
                          onClick={() => {
                            setShowYardEntryConfirmDialog(false)
                            // 라디오 버튼을 다시 'Y'로 되돌림
                            const yardEntryYesRadio = document.getElementById('yardEntryYes') as HTMLInputElement
                            if (yardEntryYesRadio) {
                              yardEntryYesRadio.checked = true
                            }
                          }}
                        >
                          취소
                        </Button>
                        <Button
                          onClick={() => {
                            setFormData(prev => ({ ...prev, externalYardEntry: 'N' as 'Y' | 'N' }))
                            setShowYardEntryConfirmDialog(false)
                          }}
                        >
                          확인
                        </Button>
                      </div>
                    </div>
                  </DialogContent>
                </Dialog>
                </div>
              </div>

              {/* 계약성립조건 */}
              <div className="space-y-4 grid grid-cols-2 col-span-2">
                <div className="space-y-3">
                <Label className="text-base font-medium">계약성립조건</Label>

                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="regularVendorRegistration"
                      checked={formData.contractEstablishmentConditions.regularVendorRegistration}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, regularVendorRegistration: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="regularVendorRegistration">정규업체 등록(실사 포함) 시</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="projectAward"
                      checked={formData.contractEstablishmentConditions.projectAward}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, projectAward: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="projectAward">프로젝트 수주 시</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="ownerApproval"
                      checked={formData.contractEstablishmentConditions.ownerApproval}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, ownerApproval: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="ownerApproval">선주 승인 시</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="establishmentOther"
                      checked={formData.contractEstablishmentConditions.other}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, other: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="establishmentOther">기타</Label>
                  </div>
                </div>
                                {/* 계약해지조건 */}
                                <div className="space-y-4 flex-1">
                  <Label className="text-base font-medium">계약해지조건</Label>
                  <div className="space-y-3">
                    <div className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        id="standardTermination"
                        checked={formData.contractTerminationConditions.standardTermination}
                        onChange={(e) => setFormData(prev => ({ ...prev, contractTerminationConditions: { ...prev.contractTerminationConditions, standardTermination: e.target.checked } }))}
                        className="rounded"
                      />
                      <Label htmlFor="standardTermination">표준 계약해지조건</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        id="projectNotAwarded"
                        checked={formData.contractTerminationConditions.projectNotAwarded}
                        onChange={(e) => setFormData(prev => ({ ...prev, contractTerminationConditions: { ...prev.contractTerminationConditions, projectNotAwarded: e.target.checked } }))}
                        className="rounded"
                      />
                      <Label htmlFor="projectNotAwarded">프로젝트 미수주 시</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        id="terminationOther"
                        checked={formData.contractTerminationConditions.other}
                        onChange={(e) => setFormData(prev => ({ ...prev, contractTerminationConditions: { ...prev.contractTerminationConditions, other: e.target.checked } }))}
                        className="rounded"
                      />
                      <Label htmlFor="terminationOther">기타</Label>
                    </div>
                  </div>
                </div>
              </div>

              {/* 연동제적용과 계약해지조건을 같은 줄에 배치 */}
              <div className="flex gap-8">



              </div>

              <div className="space-y-2 col-span-2">
                <Label htmlFor="notes">비고</Label>
                <Textarea
                  value={formData.notes}
                  onChange={(e) => setFormData(prev => ({ ...prev, notes: e.target.value }))}
                  placeholder="비고사항을 입력하세요"
                  rows={4}
                />
              </div>
            </div>
          </CardContent>
        </Card>
      </TabsContent>


      {/* 계약첨부문서 탭 */}
      <TabsContent value="documents" className="space-y-6">
        <ContractDocuments
          contractId={contractId}
          userId={userId?.toString() || "1"}
        />
      </TabsContent>
      </Tabs>
        
        {/* 저장 버튼 */}
        <div className="flex justify-end mt-6 pt-4 border-t border-gray-200">
          <Button 
            onClick={handleSaveContractInfo}
            disabled={isLoading}
            className="flex items-center gap-2"
          >
            {isLoading ? (
              <LoaderIcon className="w-4 h-4 animate-spin" />
            ) : (
              <Save className="w-4 h-4" />
            )}
            계약 정보 저장
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}