summaryrefslogtreecommitdiff
path: root/lib/general-contracts/detail/general-contract-items-table.tsx
blob: 15e5c926e5df61f2fad6ad61cac04940f0576147 (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
'use client'

import * as React from 'react'
import { Card, CardContent, CardHeader } from '@/components/ui/card'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Package,
  Plus,
  Trash2,
  FileSpreadsheet,
  Save,
  LoaderIcon
} from 'lucide-react'
import { toast } from 'sonner'
import { updateContractItems, getContractItems } from '../service'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { ProjectSelector } from '@/components/ProjectSelector'
import { MaterialGroupSelectorDialogSingle } from '@/components/common/material/material-group-selector-dialog-single'
import { MaterialSearchItem } from '@/lib/material/material-group-service'

interface ContractItem {
  id?: number
  projectId?: number | null
  projectName?: string
  projectCode?: string
  itemCode: string
  itemInfo: string
  materialGroupCode?: string
  materialGroupDescription?: string
  specification: string
  quantity: number
  quantityUnit: string
  totalWeight: number
  weightUnit: string
  contractDeliveryDate: string
  contractUnitPrice: number
  contractAmount: number
  contractCurrency: string
  isSelected?: boolean
  [key: string]: unknown
}

interface ContractItemsTableProps {
  contractId: number
  items: ContractItem[]
  onItemsChange: (items: ContractItem[]) => void
  onTotalAmountChange: (total: number) => void
  availableBudget?: number
  readOnly?: boolean
  contractScope?: string // 계약확정범위 (단가/금액/물량)
  deliveryType?: string // 납기종류 (단일납기/분할납기)
  contractDeliveryDate?: string // 기본정보의 계약납기일
}

// 통화 목록
const CURRENCIES = ["USD", "EUR", "KRW", "JPY", "CNY"];

// 수량 단위 목록
const QUANTITY_UNITS = ["KG", "TON", "EA", "M", "M2", "M3", "L", "ML", "G", "SET", "PCS"];

// 중량 단위 목록
const WEIGHT_UNITS = ["KG", "TON", "G", "LB", "OZ"];

export function ContractItemsTable({
  contractId,
  items,
  onItemsChange,
  onTotalAmountChange,
  availableBudget = 0,
  readOnly = false,
  contractScope = '',
  deliveryType = '',
  contractDeliveryDate = ''
}: ContractItemsTableProps) {
  // 계약확정범위에 따른 필드 활성화/비활성화
  const isQuantityDisabled = contractScope === '단가' || contractScope === '물량'
  const isTotalAmountDisabled = contractScope === '단가' || contractScope === '물량'
  // 단일납기인 경우 납기일 필드 비활성화 및 기본값 설정
  const isDeliveryDateDisabled = deliveryType === '단일납기'
  const [localItems, setLocalItems] = React.useState<ContractItem[]>(items)
  const [isSaving, setIsSaving] = React.useState(false)
  const [isLoading, setIsLoading] = React.useState(false)
  const [isEnabled, setIsEnabled] = React.useState(true)
  const [showBatchInputDialog, setShowBatchInputDialog] = React.useState(false)
  const [batchInputData, setBatchInputData] = React.useState({
    quantity: '',
    quantityUnit: 'EA',
    contractDeliveryDate: '',
    contractCurrency: 'KRW',
    contractUnitPrice: ''
  })

  // 초기 데이터 로드
  React.useEffect(() => {
    const loadItems = async () => {
      try {
        setIsLoading(true)
        const fetchedItems = await getContractItems(contractId)
        const formattedItems = fetchedItems.map(item => {
          // itemInfo에서 자재그룹 정보 파싱 (형식: "자재그룹코드 / 자재그룹명")
          let materialGroupCode = ''
          let materialGroupDescription = ''
          if (item.itemInfo) {
            const parts = item.itemInfo.split(' / ')
            if (parts.length >= 2) {
              materialGroupCode = parts[0].trim()
              materialGroupDescription = parts.slice(1).join(' / ').trim()
            } else if (parts.length === 1) {
              materialGroupCode = parts[0].trim()
            }
          }
          
          return {
            id: item.id,
            projectId: item.projectId || null,
            projectName: item.projectName || undefined,
            projectCode: item.projectCode || undefined,
            itemCode: item.itemCode || '',
            itemInfo: item.itemInfo || '',
            materialGroupCode: materialGroupCode || undefined,
            materialGroupDescription: materialGroupDescription || undefined,
            specification: item.specification || '',
            quantity: Number(item.quantity) || 0,
            quantityUnit: item.quantityUnit || 'EA',
            totalWeight: Number(item.totalWeight) || 0,
            weightUnit: item.weightUnit || 'KG',
            contractDeliveryDate: item.contractDeliveryDate || '',
            contractUnitPrice: Number(item.contractUnitPrice) || 0,
            contractAmount: Number(item.contractAmount) || 0,
            contractCurrency: item.contractCurrency || 'KRW',
            isSelected: false
          }
        }) as ContractItem[]
        setLocalItems(formattedItems as ContractItem[])
        onItemsChange(formattedItems as ContractItem[])
      } catch (error) {
        console.error('Error loading contract items:', error)
        // 기본 빈 배열로 설정
        setLocalItems([])
        onItemsChange([])
      } finally {
        setIsLoading(false)
      }
    }

    loadItems()
  }, [contractId, onItemsChange])

  // 로컬 상태와 부모 상태 동기화 (초기 로드 후에는 부모 상태 우선)
  React.useEffect(() => {
    if (items.length > 0) {
      setLocalItems(items)
    }
  }, [items])

  const handleSaveItems = async () => {
    try {
      setIsSaving(true)
      
      // validation 체크
      const errors: string[] = []
      for (let index = 0; index < localItems.length; index++) {
        const item = localItems[index]
        if (!item.itemCode) errors.push(`${index + 1}번째 품목의 품목코드`)
        if (!item.itemInfo) errors.push(`${index + 1}번째 품목의 Item 정보`)
        if (!item.quantity || item.quantity <= 0) errors.push(`${index + 1}번째 품목의 수량`)
        if (!item.contractUnitPrice || item.contractUnitPrice <= 0) errors.push(`${index + 1}번째 품목의 단가`)
        if (!item.contractDeliveryDate) errors.push(`${index + 1}번째 품목의 납기일`)
      }
      
      if (errors.length > 0) {
        toast.error(`다음 항목을 입력해주세요: ${errors.join(', ')}`)
        return
      }
      
      await updateContractItems(contractId, localItems as any)
      toast.success('품목정보가 저장되었습니다.')
    } catch (error) {
      console.error('Error saving contract items:', error)
      toast.error('품목정보 저장 중 오류가 발생했습니다.')
    } finally {
      setIsSaving(false)
    }
  }

  // 총 금액 계산
  const totalAmount = localItems.reduce((sum, item) => sum + item.contractAmount, 0)
  const totalQuantity = localItems.reduce((sum, item) => sum + item.quantity, 0)
  const totalUnitPrice = localItems.reduce((sum, item) => sum + item.contractUnitPrice, 0)
  const amountDifference = availableBudget - totalAmount
  const budgetRatio = availableBudget > 0 ? (totalAmount / availableBudget) * 100 : 0

  // 부모 컴포넌트에 총 금액 전달
  React.useEffect(() => {
    onTotalAmountChange(totalAmount)
  }, [totalAmount, onTotalAmountChange])

  // 아이템 업데이트
  const updateItem = (index: number, field: keyof ContractItem, value: string | number | boolean | undefined) => {
    const updatedItems = [...localItems]
    updatedItems[index] = { ...updatedItems[index], [field]: value }
    
    // 단가나 수량이 변경되면 금액 자동 계산
    if (field === 'contractUnitPrice' || field === 'quantity') {
      const item = updatedItems[index]
      updatedItems[index].contractAmount = item.contractUnitPrice * item.quantity
    }
    
    setLocalItems(updatedItems)
    onItemsChange(updatedItems)
  }

  // 행 추가
  const addRow = () => {
    const newItem: ContractItem = {
      projectId: null,
      itemCode: '',
      itemInfo: '',
      materialGroupCode: '',
      materialGroupDescription: '',
      specification: '',
      quantity: 0,
      quantityUnit: 'EA', // 기본 수량 단위
      totalWeight: 0,
      weightUnit: 'KG', // 기본 중량 단위
      contractDeliveryDate: '',
      contractUnitPrice: 0,
      contractAmount: 0,
      contractCurrency: 'KRW', // 기본 통화
      isSelected: false
    }
    const updatedItems = [...localItems, newItem]
    setLocalItems(updatedItems)
    onItemsChange(updatedItems)
  }

  // 선택된 행 삭제
  const deleteSelectedRows = () => {
    const selectedIndices = localItems
      .map((item, index) => item.isSelected ? index : -1)
      .filter(index => index !== -1)
    
    if (selectedIndices.length === 0) {
      toast.error("삭제할 행을 선택해주세요.")
      return
    }

    const updatedItems = localItems.filter((_, index) => !selectedIndices.includes(index))
    setLocalItems(updatedItems)
    onItemsChange(updatedItems)
    toast.success(`${selectedIndices.length}개 행이 삭제되었습니다.`)
  }

  // 전체 선택/해제
  const toggleSelectAll = (checked: boolean) => {
    const updatedItems = localItems.map(item => ({ ...item, isSelected: checked }))
    setLocalItems(updatedItems)
    onItemsChange(updatedItems)
  }

  // 일괄입력 적용
  const applyBatchInput = () => {
    if (localItems.length === 0) {
      toast.error('품목이 없습니다. 먼저 품목을 추가해주세요.')
      return
    }

    const updatedItems = localItems.map(item => {
      const updatedItem = { ...item }
      
      if (batchInputData.quantity) {
        updatedItem.quantity = parseFloat(batchInputData.quantity) || 0
      }
      if (batchInputData.quantityUnit) {
        updatedItem.quantityUnit = batchInputData.quantityUnit
      }
      if (batchInputData.contractDeliveryDate) {
        updatedItem.contractDeliveryDate = batchInputData.contractDeliveryDate
      }
      if (batchInputData.contractCurrency) {
        updatedItem.contractCurrency = batchInputData.contractCurrency
      }
      if (batchInputData.contractUnitPrice) {
        updatedItem.contractUnitPrice = parseFloat(batchInputData.contractUnitPrice) || 0
        // 단가가 변경되면 계약금액도 재계산
        updatedItem.contractAmount = updatedItem.contractUnitPrice * updatedItem.quantity
      }
      
      return updatedItem
    })

    setLocalItems(updatedItems)
    onItemsChange(updatedItems)
    setShowBatchInputDialog(false)
    toast.success('일괄입력이 적용되었습니다.')
  }


  // 통화 포맷팅
  const formatCurrency = (amount: number, currency: string = 'KRW') => {
    return new Intl.NumberFormat('ko-KR', {
      style: 'currency',
      currency: currency,
    }).format(amount)
  }

  const allSelected = localItems.length > 0 && localItems.every(item => item.isSelected)
  const someSelected = localItems.some(item => item.isSelected)

  if (isLoading) {
    return (
      <Accordion type="single" collapsible className="w-full">
        <AccordionItem value="items">
          <AccordionTrigger className="hover:no-underline">
            <div className="flex items-center gap-2">
              <Package className="w-5 h-5" />
              <span>품목 정보</span>
              <span className="text-sm text-gray-500">(로딩 중...)</span>
            </div>
          </AccordionTrigger>
          <AccordionContent>
            <div className="flex items-center justify-center py-8">
              <LoaderIcon className="w-6 h-6 animate-spin mr-2" />
              <span>품목 정보를 불러오는 중...</span>
            </div>
          </AccordionContent>
        </AccordionItem>
      </Accordion>
    )
  }

  return (
    <Accordion type="single" collapsible className="w-full">
      <AccordionItem value="items">
        <AccordionTrigger className="hover:no-underline">
          <div className="flex items-center gap-3 w-full">
            <Package className="w-5 h-5" />
            <span className="font-medium">품목 정보</span>
            <span className="text-sm text-gray-500">({localItems.length}개 품목)</span>
          </div>
        </AccordionTrigger>
        <AccordionContent>
          <Card>
            <CardHeader>
              {/* 체크박스 */}
              <div className="flex items-center gap-2 mb-4">
                <Checkbox 
                  checked={isEnabled}
                  onCheckedChange={(checked) => setIsEnabled(checked as boolean)}
                  disabled={readOnly}
                />
                <span className="text-sm font-medium">품목 정보 활성화</span>
              </div>
              
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className="text-sm text-gray-600">총 금액: {formatCurrency(totalAmount, localItems[0]?.contractCurrency || 'KRW')}</span>
                  <span className="text-sm text-gray-600">총 수량: {totalQuantity.toLocaleString()}</span>
                </div>
                {!readOnly && (
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={addRow}
                      disabled={!isEnabled}
                      className="flex items-center gap-2"
                    >
                      <Plus className="w-4 h-4" />
                      행 추가
                    </Button>
                    <Dialog open={showBatchInputDialog} onOpenChange={setShowBatchInputDialog}>
                      <DialogTrigger asChild>
                        <Button
                          variant="outline"
                          size="sm"
                          disabled={!isEnabled || localItems.length === 0}
                          className="flex items-center gap-2"
                        >
                          <FileSpreadsheet className="w-4 h-4" />
                          일괄입력
                        </Button>
                      </DialogTrigger>
                      <DialogContent className="max-w-md">
                        <DialogHeader>
                          <DialogTitle>품목 정보 일괄입력</DialogTitle>
                        </DialogHeader>
                        <div className="space-y-4 py-4">
                          <div className="flex flex-col gap-2">
                            <Label htmlFor="batch-quantity">수량</Label>
                            <Input
                              id="batch-quantity"
                              type="number"
                              value={batchInputData.quantity}
                              onChange={(e) => setBatchInputData(prev => ({ ...prev, quantity: e.target.value }))}
                              placeholder="수량 입력 (선택사항)"
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label htmlFor="batch-quantity-unit">수량단위</Label>
                            <Select
                              value={batchInputData.quantityUnit}
                              onValueChange={(value) => setBatchInputData(prev => ({ ...prev, quantityUnit: value }))}
                            >
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {QUANTITY_UNITS.map((unit) => (
                                  <SelectItem key={unit} value={unit}>
                                    {unit}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label htmlFor="batch-delivery-date">계약납기일</Label>
                            <Input
                              id="batch-delivery-date"
                              type="date"
                              value={batchInputData.contractDeliveryDate}
                              onChange={(e) => setBatchInputData(prev => ({ ...prev, contractDeliveryDate: e.target.value }))}
                            />
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label htmlFor="batch-currency">계약통화</Label>
                            <Select
                              value={batchInputData.contractCurrency}
                              onValueChange={(value) => setBatchInputData(prev => ({ ...prev, contractCurrency: value }))}
                            >
                              <SelectTrigger>
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {CURRENCIES.map((currency) => (
                                  <SelectItem key={currency} value={currency}>
                                    {currency}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex flex-col gap-2">
                            <Label htmlFor="batch-unit-price">계약단가</Label>
                            <Input
                              id="batch-unit-price"
                              type="number"
                              value={batchInputData.contractUnitPrice}
                              onChange={(e) => {
                                // Leading zero removal
                                const val = e.target.value.replace(/^0+(?=[0-9])/, '')
                                setBatchInputData(prev => ({ ...prev, contractUnitPrice: val }))
                              }}
                              placeholder="계약단가 입력 (선택사항)"
                            />
                          </div>
                          <div className="flex justify-end gap-2 pt-4">
                            <Button
                              variant="outline"
                              onClick={() => setShowBatchInputDialog(false)}
                            >
                              취소
                            </Button>
                            <Button
                              onClick={applyBatchInput}
                            >
                              적용
                            </Button>
                          </div>
                        </div>
                      </DialogContent>
                    </Dialog>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={deleteSelectedRows}
                      disabled={!isEnabled}
                      className="flex items-center gap-2 text-red-600 hover:text-red-700"
                    >
                      <Trash2 className="w-4 h-4" />
                      행 삭제
                    </Button>
                    <Button
                      onClick={handleSaveItems}
                      disabled={isSaving || !isEnabled}
                      className="flex items-center gap-2"
                    >
                      {isSaving ? (
                        <LoaderIcon className="w-4 h-4 animate-spin" />
                      ) : (
                        <Save className="w-4 h-4" />
                      )}
                      품목정보 저장
                    </Button>
                  </div>
                )}
        </div>
        
        {/* 요약 정보 */}
        {/* <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
          <div className="space-y-1">
            <Label className="text-sm font-medium">총 계약금액</Label>
            <div className={`text-lg font-bold ${isTotalAmountDisabled ? 'text-gray-400' : 'text-primary'}`}>
              {isTotalAmountDisabled ? '-' : formatCurrency(totalAmount, localItems[0]?.contractCurrency || 'KRW')}
            </div>
          </div>
          <div className="space-y-1">
            <Label className="text-sm font-medium">가용예산 比 (비율)</Label>
            <div className={`text-lg font-bold ${budgetRatio <= 100 ? 'text-green-600' : 'text-red-600'}`}>
              {budgetRatio.toFixed(1)}%
            </div>
          </div>
        </div> */}
      </CardHeader>
      
      <CardContent>
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="border-b-2">
                <TableHead className="w-12 px-2">
                  {!readOnly && (
                    <Checkbox
                      checked={allSelected}
                      ref={(el) => {
                        if (el) (el as HTMLInputElement & { indeterminate?: boolean }).indeterminate = someSelected && !allSelected
                      }}
                      onCheckedChange={toggleSelectAll}
                      disabled={!isEnabled}
                    />
                  )}
                </TableHead>
                <TableHead className="px-3 py-3 font-semibold">프로젝트</TableHead>
                <TableHead className="px-3 py-3 font-semibold">품목코드 (PKG No.)</TableHead>
                <TableHead className="px-3 py-3 font-semibold">자재그룹</TableHead>
                <TableHead className="px-3 py-3 font-semibold">자재내역(자재그룹명)</TableHead>
                <TableHead className="px-3 py-3 font-semibold">규격</TableHead>
                <TableHead className="px-3 py-3 font-semibold text-right">수량</TableHead>
                <TableHead className="px-3 py-3 font-semibold">수량단위</TableHead>
                <TableHead className="px-3 py-3 font-semibold text-right">총 중량</TableHead>
                <TableHead className="px-3 py-3 font-semibold">중량단위</TableHead>
                <TableHead className="px-3 py-3 font-semibold">계약납기일</TableHead>
                <TableHead className="px-3 py-3 font-semibold text-right">계약단가</TableHead>
                <TableHead className="px-3 py-3 font-semibold text-right">계약금액</TableHead>
                <TableHead className="px-3 py-3 font-semibold">계약통화</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {localItems.map((item, index) => (
                <TableRow key={index} className="hover:bg-muted/30 transition-colors">
                  <TableCell className="px-2">
                    {!readOnly && (
                      <Checkbox
                        checked={item.isSelected || false}
                        onCheckedChange={(checked) =>
                          updateItem(index, 'isSelected', checked)
                        }
                        disabled={!isEnabled}
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.projectCode && item.projectName ? `${item.projectCode} - ${item.projectName}` : '-'}</span>
                    ) : (
                      <ProjectSelector
                        selectedProjectId={item.projectId || undefined}
                        onProjectSelect={(project) => {
                          updateItem(index, 'projectId', project.id)
                          updateItem(index, 'projectName', project.projectName)
                          updateItem(index, 'projectCode', project.projectCode)
                        }}
                        placeholder="프로젝트 선택"
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.itemCode || '-'}</span>
                    ) : (
                      <Input
                        value={item.itemCode}
                        onChange={(e) => updateItem(index, 'itemCode', e.target.value)}
                        placeholder="품목코드"
                        className="h-8 text-sm"
                        disabled={!isEnabled}
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.materialGroupCode || '-'}</span>
                    ) : (
                      <MaterialGroupSelectorDialogSingle
                        triggerLabel={item.materialGroupCode || "자재그룹 선택"}
                        triggerVariant="outline"
                        selectedMaterial={item.materialGroupCode ? {
                          materialGroupCode: item.materialGroupCode,
                          materialGroupDescription: item.materialGroupDescription || '',
                          displayText: `${item.materialGroupCode} - ${item.materialGroupDescription || ''}`
                        } : null}
                        onMaterialSelect={(material) => {
                          if (material) {
                            updateItem(index, 'materialGroupCode', material.materialGroupCode)
                            updateItem(index, 'materialGroupDescription', material.materialGroupDescription)
                            updateItem(index, 'itemInfo', `${material.materialGroupCode} / ${material.materialGroupDescription}`)
                          } else {
                            updateItem(index, 'materialGroupCode', '')
                            updateItem(index, 'materialGroupDescription', '')
                            updateItem(index, 'itemInfo', '')
                          }
                        }}
                        title="자재그룹 선택"
                        description="자재그룹을 검색하고 선택해주세요."
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.materialGroupDescription || item.itemInfo || '-'}</span>
                    ) : (
                      <Input
                        value={item.materialGroupDescription || item.itemInfo || ''}
                        onChange={(e) => updateItem(index, 'materialGroupDescription', e.target.value)}
                        placeholder="자재그룹명"
                        className="h-8 text-sm bg-muted/50"
                        readOnly
                        disabled={!isEnabled}
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.specification || '-'}</span>
                    ) : (
                      <Input
                        value={item.specification}
                        onChange={(e) => updateItem(index, 'specification', e.target.value)}
                        placeholder="규격"
                        className="h-8 text-sm"
                        disabled={!isEnabled}
                      />
                    )}
                  </TableCell>
                  {/* <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm text-right">{item.quantity.toLocaleString()}</span>
                    ) : (
                      <Input
                        type="number"
                        value={item.quantity}
                        onChange={(e) => updateItem(index, 'quantity', parseFloat(e.target.value) || 0)}
                        className="h-8 text-sm text-right"
                        placeholder="0"
                        disabled={!isEnabled || isQuantityDisabled}
                      />
                    )}
                  </TableCell> */}
                  <TableCell className="px-3 py-3">
                      <Input
                        type="number"
                        value={item.quantity}
                        onChange={(e) => updateItem(index, 'quantity', parseFloat(e.target.value) || 0)}
                        className="h-8 text-sm text-right"
                        placeholder="0"
                        disabled={!isEnabled}
                      />
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.quantityUnit || '-'}</span>
                    ) : (
                      <Select
                        value={item.quantityUnit}
                        onValueChange={(value) => updateItem(index, 'quantityUnit', value)}
                        disabled={!isEnabled || isQuantityDisabled}
                      >
                        <SelectTrigger className="h-8 text-sm w-20">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {QUANTITY_UNITS.map((unit) => (
                            <SelectItem key={unit} value={unit}>
                              {unit}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm text-right">{item.totalWeight.toLocaleString()}</span>
                    ) : (
                      <Input
                        type="number"
                        value={item.totalWeight}
                        onChange={(e) => updateItem(index, 'totalWeight', parseFloat(e.target.value) || 0)}
                        className="h-8 text-sm text-right"
                        placeholder="0"
                        disabled={!isEnabled || isQuantityDisabled}
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.weightUnit || '-'}</span>
                    ) : (
                      <Select
                        value={item.weightUnit}
                        onValueChange={(value) => updateItem(index, 'weightUnit', value)}
                        disabled={!isEnabled}
                      >
                        <SelectTrigger className="h-8 text-sm w-20">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {WEIGHT_UNITS.map((unit) => (
                            <SelectItem key={unit} value={unit}>
                              {unit}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.contractDeliveryDate || '-'}</span>
                    ) : (
                      <Input
                        type="date"
                        value={item.contractDeliveryDate}
                        onChange={(e) => updateItem(index, 'contractDeliveryDate', e.target.value)}
                        className="h-8 text-sm"
                        disabled={!isEnabled || isDeliveryDateDisabled}
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm text-right">{item.contractUnitPrice.toLocaleString()}</span>
                    ) : (
                      <Input
                        type="number"
                        value={item.contractUnitPrice}
                        onChange={(e) => updateItem(index, 'contractUnitPrice', parseFloat(e.target.value) || 0)}
                        className="h-8 text-sm text-right"
                        placeholder="0"
                        disabled={!isEnabled}
                      />
                    )}
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    <div className="font-semibold text-primary text-right text-sm">
                      {formatCurrency(item.contractAmount)}
                    </div>
                  </TableCell>
                  <TableCell className="px-3 py-3">
                    {readOnly ? (
                      <span className="text-sm">{item.contractCurrency || '-'}</span>
                    ) : (
                      <Select
                        value={item.contractCurrency}
                        onValueChange={(value) => updateItem(index, 'contractCurrency', value)}
                        disabled={!isEnabled}
                      >
                        <SelectTrigger className="h-8 text-sm w-20">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {CURRENCIES.map((currency) => (
                            <SelectItem key={currency} value={currency}>
                              {currency}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {/* 합계 정보 */}
        {localItems.length > 0 && (
          <div className="mt-6 flex justify-end">
            <Card className="w-80 bg-gradient-to-r from-primary/5 to-primary/10 border-primary/20">
              <CardContent className="p-6">
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">총 수량</span>
                    <span className="text-lg font-semibold">
                      {totalQuantity.toLocaleString()} {localItems[0]?.quantityUnit || 'KG'}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">총 단가</span>
                    <span className="text-lg font-semibold">
                      {formatCurrency(totalUnitPrice, localItems[0]?.contractCurrency || 'KRW')}
                    </span>
                  </div>
                  <div className="border-t pt-4">
                    <div className="flex items-center justify-between">
                      <span className="text-xl font-bold text-primary">합계 금액</span>
                      <span className="text-2xl font-bold text-primary">
                        {formatCurrency(totalAmount, localItems[0]?.contractCurrency || 'KRW')}
                      </span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        )}
            </CardContent>
          </Card>
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  )
}