Open History to see the last commit
1'use client'
2
3import { useState, useMemo } from 'react'
4import { ChevronUp, ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react'
5import type { DataTableProps, DataTableColumn } from '@/lib/reports/types'
6
7function formatCellValue(
8 value: unknown,
9 format?: DataTableColumn['format'],
10): string {
11 if (value === null || value === undefined) return '-'
12
13 switch (format) {
14 case 'number':
15 return typeof value === 'number'
16 ? new Intl.NumberFormat('en-US').format(value)
17 : String(value)
18 case 'currency':
19 return typeof value === 'number'
20 ? new Intl.NumberFormat('en-US', {
21 style: 'currency',
22 currency: 'USD',
23 }).format(value)
24 : String(value)
25 case 'percent':
26 return typeof value === 'number'
27 ? new Intl.NumberFormat('en-US', {
28 style: 'percent',
29 minimumFractionDigits: 1,
30 }).format(value / 100)
31 : String(value)
32 case 'date':
33 if (value instanceof Date) {
34 return value.toLocaleDateString('en-US')
35 }
36 if (typeof value === 'string' || typeof value === 'number') {
37 return new Date(value).toLocaleDateString('en-US')
38 }
39 return String(value)
40 case 'text':
41 default:
42 return String(value)
43 }
44}
45
46export function DataTable({
47 columns,
48 rows,
49 pageSize = 10,
50 showPagination = true,
51 striped = true,
52 compact = false,
53 sortBy: initialSortBy,
54 sortDirection: initialSortDirection = 'asc',
55}: DataTableProps) {
56 const [sortBy, setSortBy] = useState<string | undefined>(initialSortBy)
57 const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>(
58 initialSortDirection,
59 )
60 const [currentPage, setCurrentPage] = useState(0)
61
62 const sortedRows = useMemo(() => {
63 if (!sortBy) return rows
64
65 return [...rows].sort((a, b) => {
66 const aVal = a[sortBy]
67 const bVal = b[sortBy]
68
69 if (aVal === null || aVal === undefined) return 1
70 if (bVal === null || bVal === undefined) return -1
71
72 let comparison = 0
73 if (typeof aVal === 'number' && typeof bVal === 'number') {
74 comparison = aVal - bVal
75 } else {
76 comparison = String(aVal).localeCompare(String(bVal))
77 }
78
79 return sortDirection === 'asc' ? comparison : -comparison
80 })
81 }, [rows, sortBy, sortDirection])
82
83 const paginatedRows = useMemo(() => {
84 if (pageSize === 0 || !showPagination) return sortedRows
85 const start = currentPage * pageSize
86 return sortedRows.slice(start, start + pageSize)
87 }, [sortedRows, currentPage, pageSize, showPagination])
88
89 const totalPages = pageSize > 0 ? Math.ceil(rows.length / pageSize) : 1
90
91 const handleSort = (columnKey: string) => {
92 const column = columns.find((c) => c.key === columnKey)
93 if (column?.sortable === false) return
94
95 if (sortBy === columnKey) {
96 setSortDirection((prev) => (prev === 'asc' ? 'desc' : 'asc'))
97 } else {
98 setSortBy(columnKey)
99 setSortDirection('asc')
100 }
101 }
102
103 const alignClasses = {
104 left: 'text-left',
105 center: 'text-center',
106 right: 'text-right',
107 }
108
109 const cellPadding = compact ? 'px-3 py-1.5' : 'px-4 py-3'
110
111 return (
112 <div className="bg-[var(--report-card-bg)] rounded-lg border border-[var(--report-border)] overflow-hidden">
113 <div className="overflow-x-auto">
114 <table className="w-full text-sm">
115 <thead>
116 <tr className="border-b border-[var(--report-border)] bg-sky-100/50">
117 {columns.map((column) => {
118 const isSortable = column.sortable !== false
119 const isSorted = sortBy === column.key
120
121 return (
122 <th
123 key={column.key}
124 className={`${cellPadding} font-medium text-[var(--report-text-muted)] ${alignClasses[column.align || 'left']} ${isSortable ? 'cursor-pointer hover:text-[var(--report-text)] select-none' : ''}`}
125 style={column.width ? { width: column.width } : undefined}
126 onClick={() => isSortable && handleSort(column.key)}
127 >
128 <div className="flex items-center gap-1">
129 <span>{column.label}</span>
130 {isSortable &&
131 isSorted &&
132 (sortDirection === 'asc' ? (
133 <ChevronUp className="w-4 h-4" />
134 ) : (
135 <ChevronDown className="w-4 h-4" />
136 ))}
137 </div>
138 </th>
139 )
140 })}
141 </tr>
142 </thead>
143 <tbody>
144 {paginatedRows.map((row, rowIndex) => (
145 <tr
146 key={rowIndex}
147 className={`border-b border-[var(--report-border)] last:border-0 hover:bg-sky-50/50 transition-colors ${striped && rowIndex % 2 === 1 ? 'bg-sky-50/30' : ''}`}
148 >
149 {columns.map((column) => (
150 <td
151 key={column.key}
152 className={`${cellPadding} text-[var(--report-text)] ${alignClasses[column.align || 'left']}`}
153 >
154 {formatCellValue(row[column.key], column.format)}
155 </td>
156 ))}
157 </tr>
158 ))}
159 </tbody>
160 </table>
161 </div>
162
163 {showPagination && pageSize > 0 && totalPages > 1 && (
164 <div className="flex items-center justify-between px-4 py-3 border-t border-[var(--report-border)] bg-sky-50/50">
165 <span className="text-sm text-[var(--report-text-muted)]">
166 Showing {currentPage * pageSize + 1} to{' '}
167 {Math.min((currentPage + 1) * pageSize, rows.length)} of{' '}
168 {rows.length}
169 </span>
170 <div className="flex items-center gap-2">
171 <button
172 onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
173 disabled={currentPage === 0}
174 className="p-1 rounded hover:bg-sky-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
175 >
176 <ChevronLeft className="w-5 h-5 text-[var(--report-text)]" />
177 </button>
178 <span className="text-sm text-[var(--report-text)]">
179 Page {currentPage + 1} of {totalPages}
180 </span>
181 <button
182 onClick={() =>
183 setCurrentPage((p) => Math.min(totalPages - 1, p + 1))
184 }
185 disabled={currentPage >= totalPages - 1}
186 className="p-1 rounded hover:bg-sky-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
187 >
188 <ChevronRight className="w-5 h-5 text-[var(--report-text)]" />
189 </button>
190 </div>
191 </div>
192 )}
193 </div>
194 )
195}