import {
  Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography,
} from '@mui/material'
import type { MatmulMethod } from '../methods/types'

export interface CellResult {
  gflops: number
  ms: number
  sample: number
}

export type CellState = CellResult | 'pending' | 'unavailable' | 'error' | undefined

export interface ResultsTableProps {
  methods: MatmulMethod[]
  sizes: number[]
  cell(methodId: string, n: number): CellState
}

function CellContent({ state }: { state: CellState }) {
  if (state === undefined) return <span>—</span>
  if (state === 'pending') return <span>…</span>
  if (state === 'unavailable') return <Typography variant="caption" color="text.secondary">n/a</Typography>
  if (state === 'error') return <Typography variant="caption" color="error">error</Typography>
  return (
    <>
      <div>{state.gflops.toFixed(2)} GFLOP/s</div>
      <Typography variant="caption" color="text.secondary">{state.ms.toFixed(1)} ms</Typography>
    </>
  )
}

export function ResultsTable({ methods, sizes, cell }: ResultsTableProps) {
  return (
    <TableContainer component={Paper} variant="outlined">
      <Table size="small">
        <TableHead>
          <TableRow>
            <TableCell>n</TableCell>
            {methods.map((m) => (
              <TableCell key={m.id} align="right">
                {m.label}
                <Typography variant="caption" color="text.secondary" component="div">
                  {m.precision}
                </Typography>
              </TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {sizes.map((n) => (
            <TableRow key={n}>
              <TableCell>{n}</TableCell>
              {methods.map((m) => (
                <TableCell key={m.id} align="right">
                  <CellContent state={cell(m.id, n)} />
                </TableCell>
              ))}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  )
}
