summaryrefslogtreecommitdiff
path: root/lib/vendor-pool/table/vendor-pool-virtual-table.tsx
blob: 81ac804f70f631d37fada42d21aed511b2e4af21 (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
"use client"

import * as React from "react"
import {
  useReactTable,
  getCoreRowModel,
  getSortedRowModel,
  getFilteredRowModel,
  type ColumnDef,
  type SortingState,
  type ColumnFiltersState,
  flexRender,
  type Column,
} from "@tanstack/react-table"
import { useVirtualizer } from "@tanstack/react-virtual"
import { useSession } from "next-auth/react"
import { toast } from "sonner"
import { ChevronDown, ChevronUp, Search, Download, FileSpreadsheet, Upload } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { columns, type VendorPoolItem } from "./vendor-pool-table-columns"
import { createVendorPool, updateVendorPool, deleteVendorPool } from "../service"
import type { VendorPool } from "@/db/schema/avl/vendor-pool"
import { BulkInsertDialog } from "./bulk-insert-dialog"
import { ImportVendorPoolButton } from "./vendor-pool-excel-import-button"
import { exportVendorPoolToExcel, createVendorPoolTemplate } from "../excel-utils"
import { ImportResultDialog, type ImportResult } from "./import-result-dialog"

// 테이블 메타 타입
interface VendorPoolTableMeta {
  onCellUpdate?: (id: string | number, field: string, newValue: any) => Promise<void>
  onCellCancel?: (id: string | number, field: string) => void
  onAction?: (action: string, data?: any) => void
  onSaveEmptyRow?: (tempId: string) => Promise<void>
  onCancelEmptyRow?: (tempId: string) => void
  isEmptyRow?: (id: string) => boolean
  getPendingChanges?: () => Record<string, Partial<VendorPoolItem>>
}

interface VendorPoolVirtualTableProps {
  data: VendorPoolItem[]
  onRefresh?: () => void
}

// 빈 행 기본값
const createEmptyVendorPoolBase = (): Omit<VendorPool, 'id'> & { id?: string | number } => ({
  constructionSector: "",
  htDivision: "",
  discipline: "",
  equipBulkDivision: "",
  materialGroupCode: null,
  materialGroupName: null,
  similarMaterialNamePurchase: null,
  vendorCode: null,
  vendorName: "",
  taxId: null,
  faTarget: false,
  faStatus: null,
  tier: null,
  headquarterLocation: "",
  manufacturingLocation: "",
  avlVendorName: null,
  similarVendorName: null,
  isBlacklist: false,
  isBcc: false,
  purchaseOpinion: null,
  recentQuoteDate: null,
  recentQuoteNumber: null,
  recentOrderDate: null,
  recentOrderNumber: null,
  registrationDate: null,
  registrant: null,
  lastModifiedDate: null,
  lastModifier: null,
})

function Filter({ column }: { column: Column<any, unknown> }) {
  const columnFilterValue = column.getFilterValue()
  const id = column.id

  // Boolean 필터 (faTarget, isBlacklist, isBcc 등)
  if (id === 'faTarget' || id === 'isBlacklist' || id === 'isBcc') {
    return (
      <div onClick={(e) => e.stopPropagation()} className="mt-2">
        <Select
          value={(columnFilterValue as string) ?? "all"}
          onValueChange={(value) => column.setFilterValue(value === "all" ? undefined : value === "true")}
        >
          <SelectTrigger className="h-8 w-full">
            <SelectValue placeholder="All" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All</SelectItem>
            <SelectItem value="true">Yes</SelectItem>
            <SelectItem value="false">No</SelectItem>
          </SelectContent>
        </Select>
      </div>
    )
  }

  // FA Status 필터 (O 또는 빈 값)
  if (id === 'faStatus') {
    return (
      <div onClick={(e) => e.stopPropagation()} className="mt-2">
        <Select
          value={(columnFilterValue as string) ?? "all"}
          onValueChange={(value) => column.setFilterValue(value === "all" ? undefined : value)}
        >
          <SelectTrigger className="h-8 w-full">
            <SelectValue placeholder="All" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All</SelectItem>
            <SelectItem value="O">YES</SelectItem>
            <SelectItem value="X">NO</SelectItem>
          </SelectContent>
        </Select>
      </div>
    )
  }

  // 일반 텍스트 검색
  return (
    <div onClick={(e) => e.stopPropagation()} className="mt-2">
      <Input
        type="text"
        value={(columnFilterValue ?? '') as string}
        onChange={(e) => column.setFilterValue(e.target.value)}
        placeholder="Search..."
        className="h-8 w-full font-normal bg-background"
      />
    </div>
  )
}

export function VendorPoolVirtualTable({ data, onRefresh }: VendorPoolVirtualTableProps) {
  const { data: session } = useSession()

  // onRefresh를 ref로 관리하여 무한 루프 방지
  const onRefreshRef = React.useRef(onRefresh)
  React.useEffect(() => {
    onRefreshRef.current = onRefresh
  }, [onRefresh])

  // 상태 관리
  const [sorting, setSorting] = React.useState<SortingState>([])
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
  const [globalFilter, setGlobalFilter] = React.useState("")
  const [pendingChanges, setPendingChanges] = React.useState<Record<string, Partial<VendorPoolItem>>>({})
  const [isSaving, setIsSaving] = React.useState(false)
  const [emptyRows, setEmptyRows] = React.useState<Record<string, VendorPoolItem>>({})
  const [isCreating, setIsCreating] = React.useState(false)
  const [bulkInsertDialogOpen, setBulkInsertDialogOpen] = React.useState(false)
  const [importResult, setImportResult] = React.useState<ImportResult | null>(null)
  const [showImportResultDialog, setShowImportResultDialog] = React.useState(false)

  const handleImportComplete = React.useCallback((result: ImportResult) => {
    setImportResult(result)
    setShowImportResultDialog(true)
  }, [])

  const handleImportDialogClose = React.useCallback((open: boolean) => {
    setShowImportResultDialog(open)
    if (!open && importResult && importResult.successCount > 0) {
      onRefreshRef.current?.()
    }
  }, [importResult])

  // 인라인 편집 핸들러
  const handleCellUpdate = React.useCallback(async (id: string | number, field: string, newValue: any) => {
    const isEmptyRow = String(id).startsWith('temp-')

    if (isEmptyRow) {
      setEmptyRows(prev => ({
        ...prev,
        [id]: {
          ...prev[id],
          [field]: newValue
        }
      }))
    }

    setPendingChanges(prev => ({
      ...prev,
      [id]: {
        ...prev[id],
        [field]: newValue
      }
    }))
  }, [])

  // 편집 취소 핸들러
  const handleCellCancel = React.useCallback((id: string | number, field: string) => {
    const isEmptyRow = String(id).startsWith('temp-')

    if (isEmptyRow) {
      setEmptyRows(prev => ({
        ...prev,
        [id]: {
          ...prev[id],
          [field]: prev[id][field]
        }
      }))

      setPendingChanges(prev => {
        const itemChanges = { ...prev[id] }
        delete itemChanges[field]

        if (Object.keys(itemChanges).length === 0) {
          const newChanges = { ...prev }
          delete newChanges[id]
          return newChanges
        }

        return {
          ...prev,
          [id]: itemChanges
        }
      })
    } else {
      setPendingChanges(prev => {
        const itemChanges = { ...prev[id] }
        delete itemChanges[field]

        if (Object.keys(itemChanges).length === 0) {
          const newChanges = { ...prev }
          delete newChanges[id]
          return newChanges
        }

        return {
          ...prev,
          [id]: itemChanges
        }
      })
    }
  }, [])

  // 일괄 저장 핸들러
  const handleBatchSave = React.useCallback(async () => {
    if (Object.keys(pendingChanges).length === 0) return

    setIsSaving(true)
    let successCount = 0
    let errorCount = 0
    let duplicateErrors: string[] = []

    try {
      for (const [id, changes] of Object.entries(pendingChanges)) {
        try {
          const { id: _, no: __, selected: ___, ...updateData } = changes
          const updateDataWithModifier: any = {
            ...updateData,
            lastModifier: session?.user?.name || null
          }
          const result = await updateVendorPool(Number(id), updateDataWithModifier)
          if (result) {
            successCount++
          } else {
            errorCount++
          }
        } catch (error) {
          console.error(`항목 ${id} 저장 실패:`, error)

          const errorMessage = error instanceof Error ? error.message : String(error);
          if (errorMessage === 'DUPLICATE_VENDOR_POOL') {
            const changes = pendingChanges[id]
            duplicateErrors.push(`항목 ${id}: 공사부문(${changes.constructionSector}), H/T(${changes.htDivision}), 자재그룹코드(${changes.materialGroupCode}), 협력업체명(${changes.vendorName})`)
          }
          errorCount++
        }
      }

      setPendingChanges({})

      if (successCount > 0) {
        toast.success(`${successCount}개 항목이 저장되었습니다.`)
        onRefreshRef.current?.()
      }

      if (duplicateErrors.length > 0) {
        duplicateErrors.forEach(errorMsg => {
          toast.error(`중복된 항목입니다. ${errorMsg}`)
        })
      }

      const generalErrorCount = errorCount - duplicateErrors.length
      if (generalErrorCount > 0) {
        toast.error(`${generalErrorCount}개 항목 저장에 실패했습니다.`)
      }
    } catch (error) {
      console.error("Batch save error:", error)
      toast.error("저장 중 오류가 발생했습니다.")
    } finally {
      setIsSaving(false)
    }
  }, [pendingChanges, session]) // ✅ onRefresh 제거

  // 빈 행 생성
  const createEmptyRow = React.useCallback(() => {
    if (isCreating) return

    const tempId = `temp-${Date.now()}`
    const userName = session?.user?.name || null

    const emptyRow: VendorPoolItem = {
      ...createEmptyVendorPoolBase(),
      id: tempId,
      no: 0,
      selected: false,
      registrationDate: "",
      registrant: userName || "",
      lastModifiedDate: "",
      lastModifier: userName || "",
    } as unknown as VendorPoolItem

    setEmptyRows(prev => ({ ...prev, [tempId]: emptyRow }))
    setIsCreating(true)

    setPendingChanges(prev => ({
      ...prev,
      [tempId]: { ...emptyRow }
    }))
  }, [isCreating, session])

  // 빈 행 저장
  const saveEmptyRow = React.useCallback(async (tempId: string) => {
    const rowData = emptyRows[tempId]
    const changes = pendingChanges[tempId]

    if (!rowData || !changes) {
      console.error('rowData 또는 changes가 없음')
      return
    }

    const finalData = { ...rowData, ...changes }

    const requiredFields = ['constructionSector', 'htDivision', 'discipline', 'vendorName', 'materialGroupCode', 'materialGroupName', 'tier', 'headquarterLocation', 'manufacturingLocation', 'avlVendorName']

    const fieldLabels: Record<string, string> = {
      constructionSector: '공사부문',
      htDivision: 'H/T구분',
      discipline: '설계공종',
      vendorName: '협력업체명',
      materialGroupCode: '자재그룹코드',
      materialGroupName: '자재그룹명',
      tier: '등급(Tier)',
      headquarterLocation: '위치(국가)',
      manufacturingLocation: '제작/선적지(국가)',
      avlVendorName: 'AVL등재업체명'
    }

    const missingFields = requiredFields.filter(field => {
      const value = finalData[field as keyof VendorPoolItem]
      return !value || value === ''
    })

    if (missingFields.length > 0) {
      const missingFieldLabels = missingFields.map(field => fieldLabels[field]).join(', ')
      toast.error(`필수 항목을 입력해주세요: ${missingFieldLabels}`)
      return
    }

    try {
      setIsSaving(true)

      const { id: _, no: __, selected: ___, registrationDate: ____, lastModifiedDate: _____, ...createData } = finalData

      const result = await createVendorPool(createData as any)

      if (result) {
        toast.success("새 항목이 추가되었습니다.")

        setEmptyRows(prev => {
          const newRows = { ...prev }
          delete newRows[tempId]
          return newRows
        })

        setPendingChanges(prev => {
          const newChanges = { ...prev }
          delete newChanges[tempId]
          return newChanges
        })

        setIsCreating(false)
        onRefreshRef.current?.()
      }
    } catch (error) {
      console.error("빈 행 저장 실패:", error)

      const errorMessage = error instanceof Error ? error.message : String(error);
      if (errorMessage === 'DUPLICATE_VENDOR_POOL') {
        toast.error(`중복된 항목입니다. (공사부문: ${finalData.constructionSector}, H/T: ${finalData.htDivision}, 자재그룹코드: ${finalData.materialGroupCode}, 협력업체명: ${finalData.vendorName})`)
      } else {
        toast.error("저장 중 오류가 발생했습니다.")
      }
    } finally {
      setIsSaving(false)
    }
  }, [emptyRows, pendingChanges]) // ✅ onRefresh 제거

  // 빈 행 취소
  const cancelEmptyRow = React.useCallback((tempId: string) => {
    setEmptyRows(prev => {
      const newRows = { ...prev }
      delete newRows[tempId]
      return newRows
    })

    setPendingChanges(prev => {
      const newChanges = { ...prev }
      delete newChanges[tempId]
      return newChanges
    })

    setIsCreating(false)
    toast.info("새 항목 추가가 취소되었습니다.")
  }, [])

  // 데이터 병합 (빈 행 + 기존 데이터)
  const combinedData = React.useMemo(() => {
    const emptyRowList = Object.values(emptyRows)

    const updatedEmptyRows = emptyRowList.map((row, index) => ({
      ...row,
      no: -(emptyRowList.length - index)
    }))

    // 최적화: 변경사항이 없으면 기존 객체 재사용
    const updatedExistingData = data.map((row) => {
      const rowId = String(row.id)
      const pendingChange = pendingChanges[rowId]

      if (pendingChange) {
        return { ...row, ...pendingChange }
      }
      
      return row
    })

    return [...updatedEmptyRows, ...updatedExistingData]
  }, [data, emptyRows, pendingChanges])

  // 액션 핸들러
  const handleAction = React.useCallback(async (action: string, data?: any) => {
    try {
      switch (action) {
        case 'new-registration':
          createEmptyRow()
          break

        case 'bulk-import':
          setBulkInsertDialogOpen(true)
          break

        case 'excel-export':
          try {
            await exportVendorPoolToExcel(
              combinedData,
              `vendor-pool-${new Date().toISOString().split('T')[0]}.xlsx`,
              true
            )
            toast.success('Excel 파일이 다운로드되었습니다.')
          } catch (error) {
            console.error('Excel export 실패:', error)
            toast.error('Excel 내보내기에 실패했습니다.')
          }
          break

        case 'excel-template':
          try {
            await createVendorPoolTemplate(
              `vendor-pool-template-${new Date().toISOString().split('T')[0]}.xlsx`
            )
            toast.success('Excel 템플릿이 다운로드되었습니다.')
          } catch (error) {
            console.error('Excel template export 실패:', error)
            toast.error('Excel 템플릿 다운로드에 실패했습니다.')
          }
          break

        case 'delete':
          if (data?.id && confirm('정말 삭제하시겠습니까?')) {
            const success = await deleteVendorPool(Number(data.id))
            if (success) {
              toast.success('삭제가 완료되었습니다.')
              onRefreshRef.current?.()
            } else {
              toast.error('삭제에 실패했습니다.')
            }
          }
          break

        default:
          console.log('알 수 없는 액션:', action)
          toast.error('알 수 없는 액션입니다.')
      }
    } catch (error) {
      console.error('액션 처리 실패:', error)
      toast.error('액션 처리 중 오류가 발생했습니다.')
    }
  }, [createEmptyRow, combinedData]) // ✅ onRefresh 제거, combinedData 추가

  // 테이블 메타
  const tableMeta: VendorPoolTableMeta = {
    onAction: handleAction,
    onCellUpdate: handleCellUpdate,
    onCellCancel: handleCellCancel,
    onSaveEmptyRow: saveEmptyRow,
    onCancelEmptyRow: cancelEmptyRow,
    isEmptyRow: (id: string) => String(id).startsWith('temp-'),
    getPendingChanges: () => pendingChanges
  }

  // TanStack Table 설정
  const table = useReactTable({
    data: combinedData,
    columns,
    state: {
      sorting,
      columnFilters,
      globalFilter,
    },
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    columnResizeMode: "onChange",
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getRowId: (originalRow) => String(originalRow.id),
    meta: tableMeta,
  })

  // 일괄입력 핸들러
  const handleBulkInsert = React.useCallback(async (bulkData: Record<string, any>) => {
    const selectedRows = table.getFilteredSelectedRowModel().rows

    if (selectedRows.length === 0) {
      toast.error('일괄 입력할 행이 선택되지 않았습니다.')
      return
    }

    try {
      for (const row of selectedRows) {
        const rowId = String(row.original.id)

        Object.entries(bulkData).forEach(([field, value]) => {
          if (value !== undefined && value !== null && value !== '') {
            handleCellUpdate(rowId, field as keyof VendorPool, value)
          }
        })
      }

      toast.success(`${selectedRows.length}개 행에 일괄 입력이 적용되었습니다.`)
      setBulkInsertDialogOpen(false)
    } catch (error) {
      console.error('일괄입력 처리 실패:', error)
      toast.error('일괄입력 처리 중 오류가 발생했습니다.')
    }
  }, [table, handleCellUpdate]) // table dependency 추가

  // Virtual Scrolling 설정
  const tableContainerRef = React.useRef<HTMLDivElement>(null)

  const { rows } = table.getRowModel()

  const rowVirtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => tableContainerRef.current,
    estimateSize: () => 50, // 행 높이 추정값
    overscan: 10, // 화면 밖 렌더링할 행 수
  })

  const virtualRows = rowVirtualizer.getVirtualItems()
  const totalSize = rowVirtualizer.getTotalSize()

  const paddingTop = virtualRows.length > 0 ? virtualRows?.[0]?.start || 0 : 0
  const paddingBottom = virtualRows.length > 0
    ? totalSize - (virtualRows?.[virtualRows.length - 1]?.end || 0)
    : 0

  const hasPendingChanges = Object.keys(pendingChanges).length > 0

  return (
    <div className="flex flex-col flex-1 min-h-0 space-y-4">
      {/* 툴바 */}
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-2 flex-1">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="전체 검색..."
              value={globalFilter ?? ""}
              onChange={(e) => setGlobalFilter(e.target.value)}
              className="pl-8"
            />
          </div>
          <div className="text-sm text-muted-foreground">
            전체 {combinedData.length}건 중 {rows.length}건 표시
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Button
            onClick={() => handleAction('new-registration')}
            disabled={isCreating}
            variant="outline"
            size="sm"
          >
            신규등록
          </Button>

          <Button
            onClick={() => handleAction('bulk-import')}
            variant="outline"
            size="sm"
          >
            일괄입력
          </Button>

          <ImportVendorPoolButton onImportComplete={handleImportComplete} />

          <Button
            onClick={() => handleAction('excel-export')}
            variant="outline"
            size="sm"
          >
            <Download className="mr-2 h-4 w-4" />
            Excel Export
          </Button>

          <Button
            onClick={() => handleAction('excel-template')}
            variant="outline"
            size="sm"
          >
            <FileSpreadsheet className="mr-2 h-4 w-4" />
            Template
          </Button>

          <Button
            onClick={handleBatchSave}
            disabled={!hasPendingChanges || isSaving}
            variant={hasPendingChanges && !isSaving ? "default" : "outline"}
            size="sm"
          >
            {isSaving ? "저장 중..." : `저장${hasPendingChanges ? ` (${Object.keys(pendingChanges).length})` : ""}`}
          </Button>
        </div>
      </div>

      {/* 테이블 */}
      <div
        ref={tableContainerRef}
        className="relative flex-1 overflow-auto border rounded-md"
      >
        <table
          className="table-fixed border-collapse"
          style={{ width: table.getTotalSize() }}
        >
          <thead className="sticky top-0 z-10 bg-muted">
            {table.getHeaderGroups().map((headerGroup) => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    className="border-b px-4 py-2 text-left text-sm font-medium relative group"
                    style={{ width: header.getSize() }}
                  >
                    {header.isPlaceholder ? null : (
                      <>
                        <div
                          className={
                            header.column.getCanSort()
                            ? "flex items-center gap-2 cursor-pointer select-none"
                            : ""
                          }
                          onClick={header.column.getToggleSortingHandler()}
                        >
                          {flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                          {header.column.getCanSort() && (
                            <div className="flex flex-col">
                              {header.column.getIsSorted() === "asc" ? (
                                <ChevronUp className="h-4 w-4" />
                              ) : header.column.getIsSorted() === "desc" ? (
                                <ChevronDown className="h-4 w-4" />
                              ) : (
                                <div className="h-4 w-4" />
                              )}
                            </div>
                          )}
                        </div>
                        {header.column.getCanFilter() && (
                          <Filter column={header.column} />
                        )}
                        <div
                          onMouseDown={header.getResizeHandler()}
                          onTouchStart={header.getResizeHandler()}
                          className={`absolute right-0 top-0 h-full w-1 cursor-col-resize select-none touch-none hover:bg-primary/50 ${
                            header.column.getIsResizing() ? 'bg-primary' : 'bg-transparent'
                          }`}
                        />
                      </>
                    )}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody>
            {paddingTop > 0 && (
              <tr>
                <td style={{ height: `${paddingTop}px` }} />
              </tr>
            )}
            {virtualRows.map((virtualRow) => {
              const row = rows[virtualRow.index]
              const isEmptyRow = String(row.original.id).startsWith('temp-')
              
              return (
                <tr
                  key={row.id}
                  data-index={virtualRow.index}
                  ref={rowVirtualizer.measureElement}
                  data-row-id={row.id}
                  className={isEmptyRow ? "bg-blue-50 border-blue-200" : "hover:bg-muted/50"}
                >
                  {row.getVisibleCells().map((cell) => (
                    <td
                      key={cell.id}
                      className="border-b px-4 py-2 text-sm whitespace-normal break-words"
                      style={{ width: cell.column.getSize() }}
                    >
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </td>
                  ))}
                </tr>
              )
            })}
            {paddingBottom > 0 && (
              <tr>
                <td style={{ height: `${paddingBottom}px` }} />
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <BulkInsertDialog
        open={bulkInsertDialogOpen}
        onOpenChange={setBulkInsertDialogOpen}
        onSubmit={handleBulkInsert}
      />

      <ImportResultDialog
        open={showImportResultDialog}
        onOpenChange={handleImportDialogClose}
        result={importResult}
      />
    </div>
  )
}