import { For, Show, type Component } from 'solid-js'

import CircularProgress from '@suid/material/CircularProgress'
import Table from '@suid/material/Table'
import TableBody from '@suid/material/TableBody'
import TableCell from '@suid/material/TableCell'
import TableHead from '@suid/material/TableHead'
import TableRow from '@suid/material/TableRow'
import Typography from '@suid/material/Typography'

import type { LeaderboardRow } from '../types'

function formatDuration(durationSec: number): string {
  const minutes = Math.floor(durationSec / 60)
  return `${minutes}m`
}

export type LeaderboardTableProps = {
  rows: LeaderboardRow[]
  loading?: boolean
  emptyMessage?: string
  maxRows?: number
  ariaLabel?: string
}

const LeaderboardTable: Component<LeaderboardTableProps> = (props) => {
  const maxRows = (): number => Math.max(1, props.maxRows ?? 10)

  return (
    <Show when={!props.loading} fallback={<CircularProgress />}>
      <Show
        when={props.rows.length > 0}
        fallback={
          <Typography sx={{ opacity: 0.8 }}>
            {props.emptyMessage ?? 'Aucun score pour le moment.'}
          </Typography>
        }
      >
        <Table size="small" aria-label={props.ariaLabel ?? 'top-10-leaderboard'}>
          <TableHead>
            <TableRow>
              <TableCell>Rang</TableCell>
              <TableCell>Joueur</TableCell>
              <TableCell align="right">Score</TableCell>
              <TableCell align="right">Questions</TableCell>
              <TableCell align="right">Taux de réussite</TableCell>
              <TableCell align="right">Durée</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            <For each={props.rows.slice(0, maxRows())}>
              {(row, idx) => (
                <TableRow>
                  <TableCell>#{idx() + 1}</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>{row.player}</TableCell>
                  <TableCell align="right">{row.score}</TableCell>
                  <TableCell align="right">{row.questions}</TableCell>
                  <TableCell align="right">{row.successRate}%</TableCell>
                  <TableCell align="right">{formatDuration(row.durationSec)}</TableCell>
                </TableRow>
              )}
            </For>
          </TableBody>
        </Table>
      </Show>
    </Show>
  )
}

export default LeaderboardTable
