import { useEffect } from "react"
import {
  Box,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Checkbox,
  Typography,
  useTheme,
  useMediaQuery,
} from "@mui/material"
import { useTranslation } from "react-i18next"
import { ProcessedRunnerModel } from "../../../../../../../components/VirtualTicket/shared/EntityTypes.ts"
import { formatTime } from "../../Splits/components/utils/chartDataTransform.ts"
import { hasChipDownload } from "../../../../../shared/functions.ts"

interface CompactRunnerTableProps {
  runners: ProcessedRunnerModel[]
  selectedRunners: string[]
  onSelectionChange: (runnerIds: string[]) => void
}

export default function CompactRunnerTable({
  runners,
  selectedRunners,
  onSelectionChange,
}: CompactRunnerTableProps) {
  const { t } = useTranslation()
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down("md"))

  const selectableRunnerIds = runners
    .filter((r) => r.stage.position && hasChipDownload(r))
    .map((r) => r.id)

  useEffect(() => {
    // Note: Removed auto-refill behavior. Users can now have 0 selected runners.
    // Initial selection is handled by the parent component (FootOSplits)
  }, [runners])

  const handleToggleRunner = (runnerId: string) => {
    if (!selectableRunnerIds.includes(runnerId)) return

    const newSelection = selectedRunners.includes(runnerId)
      ? selectedRunners.filter((id) => id !== runnerId)
      : [...selectedRunners, runnerId]

    onSelectionChange(newSelection)
  }

  const handleSelectAll = () => {
    if (selectedRunners.length === selectableRunnerIds.length) {
      onSelectionChange([])
    } else {
      onSelectionChange(selectableRunnerIds)
    }
  }

  const isAllSelected =
    selectableRunnerIds.length > 0 && selectedRunners.length === selectableRunnerIds.length
  const isIndeterminate =
    selectedRunners.length > 0 && selectedRunners.length < selectableRunnerIds.length

  return (
    <Paper sx={{ height: "100%", display: "flex", flexDirection: "column" }}>
      <Box sx={{ p: 2, borderBottom: 1, borderColor: "divider" }}>
        <Typography variant="h6" sx={{ mb: 1 }}>
          {t("Graphs.RunnerSelection")}
        </Typography>
        {selectableRunnerIds.length > 0 && (
          <Typography variant="body2" color="text.secondary">
            {t("Graphs.SelectedCount", {
              count: selectedRunners.length,
              total: selectableRunnerIds.length,
            })}
          </Typography>
        )}
      </Box>

      <TableContainer
        sx={{
          flex: 1,
          overflowY: isMobile ? "auto" : "visible",
        }}
      >
        <Table size="small" stickyHeader>
          <TableHead>
            <TableRow>
              <TableCell padding="checkbox">
                <Checkbox
                  indeterminate={isIndeterminate}
                  checked={isAllSelected}
                  onChange={handleSelectAll}
                  size="small"
                />
              </TableCell>
              <TableCell>{t("Results.Position")}</TableCell>
              <TableCell>{t("Results.Name")}</TableCell>
              <TableCell align="right">{t("Results.Time")}</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {runners.map((runner) => {
              const isSelectable = !!runner.stage.position && hasChipDownload(runner)
              const isChecked = selectedRunners.includes(runner.id)
              return (
                <TableRow
                  key={runner.id}
                  hover={isSelectable}
                  selected={isChecked}
                  onClick={() => {
                    if (isSelectable) handleToggleRunner(runner.id)
                  }}
                  sx={{
                    cursor: isSelectable ? "pointer" : "default",
                    opacity: isSelectable ? 1 : 0.5,
                  }}
                >
                  <TableCell padding="checkbox">
                    <Checkbox
                      checked={isChecked}
                      onChange={() => handleToggleRunner(runner.id)}
                      size="small"
                      disabled={!isSelectable}
                    />
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" sx={{ fontWeight: "bold" }}>
                      {runner.stage.position || "-"}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" noWrap>
                      {runner.full_name}
                    </Typography>
                    {runner.club && (
                      <Typography
                        variant="caption"
                        color="text.secondary"
                        sx={{ display: "block" }}
                      >
                        {runner.club.short_name}
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell align="right">
                    <Typography variant="body2" noWrap>
                      {runner.stage.time_seconds ? formatTime(runner.stage.time_seconds) : "-"}
                    </Typography>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </Paper>
  )
}
