"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import KeyboardArrowLeftRoundedIcon from "@mui/icons-material/KeyboardArrowLeftRounded";
import KeyboardArrowRightRoundedIcon from "@mui/icons-material/KeyboardArrowRightRounded";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";
import type { RgcDecisionRow } from "../data/rgc-decision-data";
import type { RgcDecisionLanguage } from "../data/rgc-decision-i18n";
import { getRgcDecisionColumns } from "./rgc-decision-table-config";
import { RgcDecisionTableCell } from "./rgc-decision-table-cells";

type Props = {
  rows: RgcDecisionRow[];
  language: RgcDecisionLanguage;
  loading?: boolean;
  error?: string | null;
};

const PAGE_SIZE = 8;
const ROW_HEIGHT = 68;

export function RgcDecisionTable({ rows, language, loading = false, error = null }: Props) {
  const theme = useTheme();
  const router = useRouter();
  const isDark = theme.palette.mode === "dark";
  const [requestedPage, setRequestedPage] = useState(1);
  const columns = useMemo(() => getRgcDecisionColumns(language), [language]);
  const pageCount = Math.max(1, Math.ceil(rows.length / PAGE_SIZE));
  const page = Math.min(requestedPage, pageCount);
  const pageRows = useMemo(() => {
    const start = (page - 1) * PAGE_SIZE;
    return rows.slice(start, start + PAGE_SIZE);
  }, [page, rows]);
  const minimumWidth = columns.reduce((total, column) => total + column.width, 0);

  return (
    <Box sx={{ width: "100%", flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
      <TableContainer sx={{ flex: 1, overflowX: "auto", overflowY: "auto" }}>
        <Table stickyHeader sx={{ minWidth: minimumWidth, tableLayout: "fixed" }}>
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.id}
                  align={column.align ?? "left"}
                  sx={{
                    width: column.width,
                    minWidth: column.minWidth,
                    height: 56,
                    px: 1.5,
                    bgcolor: isDark ? "#203A59" : "#DDEEFF",
                    color: theme.palette.text.secondary,
                    borderRight: "1px solid",
                    borderRightColor: isDark ? alpha("#FFFFFF", 0.12) : "#CFE0F0",
                    borderBottom: "1px solid",
                    borderBottomColor: isDark ? alpha("#FFFFFF", 0.18) : "#D6E2ED",
                    fontSize: 13,
                    fontWeight: 600,
                    whiteSpace: "nowrap",
                    "&:last-of-type": { borderRight: "none" },
                  }}
                >
                  {column.label}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>

          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={columns.length} align="center" sx={{ height: ROW_HEIGHT * 5, borderBottom: "none" }}>
                  <CircularProgress size={30} />
                </TableCell>
              </TableRow>
            ) : error && rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={columns.length} align="center" sx={{ height: ROW_HEIGHT * 5, borderBottom: "none" }}>
                  <Typography color="error">{error}</Typography>
                </TableCell>
              </TableRow>
            ) : pageRows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={columns.length} align="center" sx={{ height: ROW_HEIGHT * 5, borderBottom: "none" }}>
                  <Typography sx={{ color: theme.palette.text.secondary, fontSize: 14 }}>
                    {language === "kh"
                      ? "រកមិនឃើញសេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាលទេ។"
                      : "No RGC Decisions found."}
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              pageRows.map((row, rowIndex) => {
                const displayNumber = (page - 1) * PAGE_SIZE + rowIndex + 1;
                return (
                  <TableRow key={row.id} sx={{ height: ROW_HEIGHT, "&:last-of-type td": { borderBottom: "none" } }}>
                    {columns.map((column) => (
                      <TableCell
                        key={column.id}
                        align={column.align ?? "left"}
                        sx={{
                          width: column.width,
                          minWidth: column.minWidth,
                          height: ROW_HEIGHT,
                          px: 1.5,
                          py: 1.1,
                          borderRight: "1px solid",
                          borderRightColor: isDark ? alpha("#FFFFFF", 0.12) : "#E2E8F0",
                          borderBottom: "1px solid",
                          borderBottomColor: isDark ? alpha("#FFFFFF", 0.14) : "#E2E8F0",
                          "&:last-of-type": { borderRight: "none" },
                        }}
                      >
                        <RgcDecisionTableCell
                          row={row}
                          columnId={column.id}
                          displayNumber={displayNumber}
                          onViewDetail={(selected) => router.push(`/cdc/rgc-decision/${selected.id}`)}
                        />
                      </TableCell>
                    ))}
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Box sx={{ minHeight: 68, px: 2, py: 1.3, display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", borderTop: "1px solid", borderTopColor: theme.palette.divider }}>
        <Button variant="outlined" disabled={loading || page <= 1} startIcon={<KeyboardArrowLeftRoundedIcon />} onClick={() => setRequestedPage(Math.max(1, page - 1))} sx={{ justifySelf: "start", textTransform: "none" }}>
          {language === "kh" ? "មុន" : "Previous"}
        </Button>
        <Box sx={{ minWidth: 40, height: 40, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: "8px", bgcolor: alpha(theme.palette.primary.main, isDark ? 0.16 : 0.08), fontWeight: 700 }}>
          {page}
        </Box>
        <Button variant="outlined" disabled={loading || page >= pageCount} endIcon={<KeyboardArrowRightRoundedIcon />} onClick={() => setRequestedPage(Math.min(pageCount, page + 1))} sx={{ justifySelf: "end", textTransform: "none" }}>
          {language === "kh" ? "បន្ទាប់" : "Next"}
        </Button>
      </Box>
    </Box>
  );
}

export default RgcDecisionTable;
