import * as React from 'react'
import { cn } from '@/lib/utils'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from './table'

export interface DataTableColumn<TData> {
  key: string
  header: React.ReactNode
  cell?: (row: TData, index: number) => React.ReactNode
  accessor?: keyof TData
  className?: string
}

export interface DataTableProps<TData> extends React.HTMLAttributes<HTMLDivElement> {
  columns: DataTableColumn<TData>[]
  data: TData[]
  emptyText?: React.ReactNode
}

function DataTable<TData extends Record<string, unknown>>({
  columns,
  data,
  emptyText = 'No results.',
  className,
  ...props
}: DataTableProps<TData>) {
  return (
    <div className={cn('w-full overflow-auto rounded-lg border border-border-tertiary', className)} {...props}>
      <Table>
        <TableHeader>
          <TableRow>
            {columns.map((column) => (
              <TableHead key={column.key} className={column.className}>
                {column.header}
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {data.length > 0 ? (
            data.map((row, rowIndex) => (
              <TableRow key={rowIndex}>
                {columns.map((column) => (
                  <TableCell key={column.key} className={column.className}>
                    {column.cell
                      ? column.cell(row, rowIndex)
                      : column.accessor
                        ? String(row[column.accessor] ?? '')
                        : null}
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={columns.length} className="h-24 text-center text-text-tertiary">
                {emptyText}
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  )
}

export { DataTable }
