import type { ReactNode } from 'react'
import Alert from '@mui/material/Alert'
import Skeleton from '@mui/material/Skeleton'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'

export type AdminTableColumn = {
  key: string
  label: string
  align?: 'left' | 'right' | 'center'
}

type Props = {
  columns: AdminTableColumn[]
  children: ReactNode
  loading?: boolean
  error?: string | null
  skeletonRows?: number
}

export function AdminTable({ columns, children, loading, error, skeletonRows = 3 }: Props) {
  return (
    <Table size="small">
      <TableHead>
        <TableRow>
          {columns.map((col) => (
            <TableCell key={col.key} align={col.align}>
              {col.label}
            </TableCell>
          ))}
        </TableRow>
      </TableHead>
      <TableBody>
        {error && (
          <TableRow>
            <TableCell colSpan={columns.length}>
              <Alert severity="error">{error}</Alert>
            </TableCell>
          </TableRow>
        )}
        {loading && !error && (
          <>
            {Array.from({ length: skeletonRows }).map((_, i) => (
              <TableRow key={i}>
                {columns.map((col) => (
                  <TableCell key={col.key}>
                    <Skeleton />
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </>
        )}
        {!loading && !error && children}
      </TableBody>
    </Table>
  )
}
