import { ReactNode, useState } from 'react' import { Table, Flex, Text, Spinner } from '@chakra-ui/react' import { FiChevronUp, FiChevronDown } from 'react-icons/fi' interface Column { header: string accessor: keyof T | ((row: T) => ReactNode) width?: string } interface DataTableProps { columns: Column[] data: T[] onRowClick?: (row: T) => void loading?: boolean } export default function DataTable({ columns, data, onRowClick, loading, }: DataTableProps) { const [sortCol, setSortCol] = useState(null) const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc') const handleSort = (header: string) => { if (sortCol === header) { setSortDir(sortDir === 'asc' ? 'desc' : 'asc') } else { setSortCol(header) setSortDir('asc') } } let sorted = [...data] if (sortCol) { const col = columns.find((c) => c.header === sortCol) if (col && typeof col.accessor === 'string') { sorted.sort((a, b) => { const av = (a as any)[col.accessor as string] const bv = (b as any)[col.accessor as string] if (av == null && bv == null) return 0 if (av == null) return sortDir === 'asc' ? 1 : -1 if (bv == null) return sortDir === 'asc' ? -1 : 1 if (typeof av === 'string') { return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av) } if (typeof av === 'number') { return sortDir === 'asc' ? av - bv : bv - av } return 0 }) } } const getCellValue = (row: T, col: Column): string => { if (typeof col.accessor === 'function') return '' return String((row as any)[col.accessor] ?? '') } const getCellNode = (row: T, col: Column): ReactNode => { if (typeof col.accessor === 'function') return col.accessor(row) return String((row as any)[col.accessor] ?? '') } return ( {columns.map((col) => ( handleSort(col.header)} cursor="pointer" userSelect="none" textTransform="uppercase" fontSize="2xs" letterSpacing="wider" fontWeight="semibold" color="fg.muted" py={3} px={4} _hover={{ color: 'fg' }} style={{ width: col.width }} > {col.header} {sortCol === col.header && ( {sortDir === 'asc' ? : } )} ))} {loading ? ( Loading... ) : sorted.length === 0 ? ( No results found ) : ( sorted.map((row, i) => ( onRowClick?.(row)} cursor={onRowClick ? 'pointer' : 'default'} _hover={{ bg: 'bg.subtle' }} borderBottomWidth="1px" borderColor="border" bg={i % 2 === 0 ? 'transparent' : 'bg.subtle'} > {columns.map((col) => ( {getCellNode(row, col)} ))} )) )} ) }