"use client";

import { useMemo, useState } from "react";

import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded";
import RemoveRedEyeOutlinedIcon from "@mui/icons-material/RemoveRedEyeOutlined";

import {
  Avatar,
  Box,
  Button,
  Link,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";

import type { MinistryRgcDecisionRow } from "../data/ministry-rgc-decision-data";
import { MinistryRgcDecisionStatusChip } from "./ministry-rgc-decision-status-chip";
import {
  ministryRgcDecisionText,
  normalizeMinistryRgcDecisionLanguage,
} from "../ministry-rgc-decision-i18n";

const ROWS_PER_PAGE = 10;

/**
 * Converts rich-text editor HTML into clean one-line text for table cells.
 * It also handles HTML that was encoded before being returned by the API,
 * for example: &lt;span style="..."&gt;Decision&lt;/span&gt;.
 */
function richTextToPlainText(
  value: string | null | undefined,
): string {
  if (!value) {
    return "";
  }

  let text = String(value);

  // Decode common HTML entities first. This is important when the API returns
  // escaped rich-text HTML instead of normal HTML.
  const decodeEntities = (input: string): string => {
    if (typeof document !== "undefined") {
      const textarea = document.createElement("textarea");
      textarea.innerHTML = input;
      return textarea.value;
    }

    return input
      .replace(/&nbsp;/gi, " ")
      .replace(/&amp;/gi, "&")
      .replace(/&lt;/gi, "<")
      .replace(/&gt;/gi, ">")
      .replace(/&quot;/gi, '"')
      .replace(/&#39;/gi, "'");
  };

  // Two passes cover both normal HTML and double-encoded HTML safely.
  for (let pass = 0; pass < 2; pass += 1) {
    text = decodeEntities(text)
      .replace(/<br\s*\/?>/gi, " ")
      .replace(/<\/p>/gi, " ")
      .replace(/<\/div>/gi, " ")
      .replace(/<\/li>/gi, " ")
      .replace(/<[^>]*>/g, " ");
  }

  return text
    .replace(/\u00A0/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function createPageNumbers(
  currentPage: number,
  totalPages: number,
): Array<number | "..."> {
  if (totalPages <= 7) {
    return Array.from(
      { length: totalPages },
      (_, index) => index + 1,
    );
  }

  if (currentPage <= 4) {
    return [1, 2, 3, 4, 5, "...", totalPages];
  }

  if (currentPage >= totalPages - 3) {
    return [
      1,
      "...",
      totalPages - 4,
      totalPages - 3,
      totalPages - 2,
      totalPages - 1,
      totalPages,
    ];
  }

  return [
    1,
    "...",
    currentPage - 1,
    currentPage,
    currentPage + 1,
    "...",
    totalPages,
  ];
}

function PaginationFooter({
  currentPage,
  totalPages,
  onPageChange,
}: {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
}) {
  const theme = useTheme();
  const { language } = useAppLanguage();
  const currentLanguage = normalizeMinistryRgcDecisionLanguage(language);
  const text = ministryRgcDecisionText[currentLanguage];
  const isDark = theme.palette.mode === "dark";

  const pages = useMemo(
    () => createPageNumbers(currentPage, totalPages),
    [currentPage, totalPages],
  );

  const navButtonSx = {
    height: 38,
    minWidth: 106,
    px: 1.4,
    borderRadius: "8px",
    borderColor: theme.palette.divider,
    bgcolor: theme.palette.background.paper,
    color: theme.palette.text.primary,
    textTransform: "none",
    fontSize: 12,
    fontWeight: 600,
    boxShadow: "none",

    "&:hover": {
      borderColor: theme.palette.primary.main,
      bgcolor: alpha(
        theme.palette.primary.main,
        isDark ? 0.12 : 0.05,
      ),
      boxShadow: "none",
    },

    "&.Mui-disabled": {
      color: theme.palette.action.disabled,
      borderColor: theme.palette.divider,
      bgcolor: theme.palette.action.disabledBackground,
    },
  };

  return (
    <Stack
      direction={{
        xs: "column",
        sm: "row",
      }}
      spacing={{
        xs: 1.2,
        sm: 0,
      }}
      sx={{
        width: "100%",
        px: 2,
        py: 1.4,
        alignItems: "center",
        justifyContent: "space-between",
        borderTop: `1px solid ${theme.palette.divider}`,
        bgcolor: theme.palette.background.paper,
      }}
    >
      <Box
        sx={{
          width: {
            xs: "100%",
            sm: 120,
          },
          display: "flex",
          justifyContent: {
            xs: "center",
            sm: "flex-start",
          },
        }}
      >
        <Button
          variant="outlined"
          disabled={currentPage <= 1}
          startIcon={
            <ArrowBackRoundedIcon
              sx={{ fontSize: 16 }}
            />
          }
          onClick={() =>
            onPageChange(currentPage - 1)
          }
          sx={navButtonSx}
        >
          {text.previous}
        </Button>
      </Box>

      <Stack
        direction="row"
        spacing={0.6}
        sx={{
          flex: 1,
          minWidth: 0,
          alignItems: "center",
          justifyContent: "center",
          flexWrap: "wrap",
        }}
      >
        {pages.map((page, index) => {
          if (page === "...") {
            return (
              <Box
                key={`ellipsis-${index}`}
                sx={{
                  width: 34,
                  height: 34,
                  display: "grid",
                  placeItems: "center",
                  color: theme.palette.text.secondary,
                  fontSize: 12,
                  fontWeight: 500,
                }}
              >
                ...
              </Box>
            );
          }

          const active = page === currentPage;

          return (
            <Button
              key={page}
              variant="text"
              onClick={() => onPageChange(page)}
              sx={{
                minWidth: 36,
                width: 36,
                height: 36,
                p: 0,
                borderRadius: "8px",
                color: active
                  ? theme.palette.text.primary
                  : theme.palette.text.secondary,
                bgcolor: active
                  ? alpha(
                      theme.palette.primary.main,
                      isDark ? 0.16 : 0.06,
                    )
                  : "transparent",
                fontSize: 12,
                fontWeight: active ? 700 : 500,

                "&:hover": {
                  bgcolor: active
                    ? alpha(
                        theme.palette.primary.main,
                        isDark ? 0.2 : 0.1,
                      )
                    : alpha(
                        theme.palette.primary.main,
                        isDark ? 0.12 : 0.05,
                      ),
                },
              }}
            >
              {page}
            </Button>
          );
        })}
      </Stack>

      <Box
        sx={{
          width: {
            xs: "100%",
            sm: 120,
          },
          display: "flex",
          justifyContent: {
            xs: "center",
            sm: "flex-end",
          },
        }}
      >
        <Button
          variant="outlined"
          disabled={currentPage >= totalPages}
          endIcon={
            <ArrowForwardRoundedIcon
              sx={{ fontSize: 16 }}
            />
          }
          onClick={() =>
            onPageChange(currentPage + 1)
          }
          sx={navButtonSx}
        >
          {text.next}
        </Button>
      </Box>
    </Stack>
  );
}

export function MinistryRgcDecisionTable({
  rows,
  onViewDetail,
  loading = false,
}: {
  rows: MinistryRgcDecisionRow[];
  onViewDetail?: (
    row: MinistryRgcDecisionRow,
  ) => void;
  loading?: boolean;
}) {
  const theme = useTheme();
  const { language } = useAppLanguage();
  const currentLanguage = normalizeMinistryRgcDecisionLanguage(language);
  const text = ministryRgcDecisionText[currentLanguage];
  const isDark = theme.palette.mode === "dark";

  const [currentPage, setCurrentPage] =
    useState(1);

  const totalPages = Math.max(
    1,
    Math.ceil(rows.length / ROWS_PER_PAGE),
  );

  const safeCurrentPage = useMemo(
    () =>
      Math.min(
        Math.max(currentPage, 1),
        totalPages,
      ),
    [currentPage, totalPages],
  );

  const paginatedRows = useMemo(() => {
    const startIndex =
      (safeCurrentPage - 1) * ROWS_PER_PAGE;

    return rows.slice(
      startIndex,
      startIndex + ROWS_PER_PAGE,
    );
  }, [rows, safeCurrentPage]);

  const handlePageChange = (page: number) => {
    const nextPage = Math.min(
      Math.max(page, 1),
      totalPages,
    );

    setCurrentPage(nextPage);
  };

  const headerCellSx = {
    height: 48,
    px: 1.5,
    py: 0,
    color: theme.palette.text.secondary,
    bgcolor: isDark
      ? alpha(theme.palette.primary.main, 0.16)
      : "#DCEEFF",
    borderColor: theme.palette.divider,
    fontSize: 12,
    fontWeight: 500,
    lineHeight: "18px",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
  };

  const bodyCellSx = {
    height: 56,
    px: 1.5,
    py: 0,
    color: theme.palette.text.primary,
    borderColor: theme.palette.divider,
    fontSize: 13,
    fontWeight: 500,
    lineHeight: "16px",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
  };

  return (
    <Paper
      elevation={0}
      sx={{
        width: "100%",
        maxWidth: "100%",
        overflow: "hidden",
        borderRadius: "10px",
        border: `1px solid ${theme.palette.divider}`,
        bgcolor: theme.palette.background.paper,
      }}
    >
      <TableContainer
        sx={{
          width: "100%",
          maxWidth: "100%",
          overflowX: "auto",

          "&::-webkit-scrollbar": {
            height: 8,
          },

          "&::-webkit-scrollbar-track": {
            bgcolor: isDark
              ? alpha("#FFFFFF", 0.06)
              : "#F2F4F7",
          },

          "&::-webkit-scrollbar-thumb": {
            bgcolor: isDark
              ? alpha("#FFFFFF", 0.22)
              : "#C7CDD6",
            borderRadius: 99,
          },
        }}
      >
        <Table
          sx={{
            minWidth: 2200, // 🔥 បន្ថែមความกว้าง table ដើម្បីรองรับ column Linked Issues
            tableLayout: "fixed",
          }}
        >
          <TableHead>
            <TableRow>
              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 60,
                }}
              >
                {text.no}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 150,
                }}
              >
                {text.ministry}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 420,
                }}
              >
                {text.rgcDecision}
              </TableCell>

              {/* 🔥 បន្ថែម Column Linked Issues នៅពីក្រោយ RGC's Decision */}
              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 260,
                }}
              >
                {text.linkedIssues}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 150,
                }}
              >
                {text.meetingDate}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 150,
                }}
              >
                {text.category}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 150,
                }}
              >
                {text.status}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 170,
                }}
              >
                {text.focalPerson}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 220,
                }}
              >
                {text.sourceOfVerification}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 200,
                }}
              >
                {text.verificationLink}
              </TableCell>

              <TableCell
                sx={{
                  ...headerCellSx,
                  width: 150,
                }}
              >
                {text.action}
              </TableCell>
            </TableRow>
          </TableHead>

          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell
                  colSpan={11} // 🔥 ប្តូរជា 11 ព្រោះមាន 11 Columns សរុប
                  sx={{
                    height: 160,
                    textAlign: "center",
                    color: theme.palette.text.secondary,
                    borderColor: theme.palette.divider,
                    fontSize: 13,
                  }}
                >
                  {text.loadingDecisions}
                </TableCell>
              </TableRow>
            ) : null}

            {!loading &&
              paginatedRows.map((row, index) => {
                const rowNumber =
                  (safeCurrentPage - 1) *
                    ROWS_PER_PAGE +
                  index +
                  1;

                const decisionText =
                  richTextToPlainText(row.decision) || "-";

                const verificationText =
                  richTextToPlainText(row.sourceOfVerification) || "-";

                const issuesText =
                  Array.isArray(row.issues) && row.issues.length > 0
                    ? row.issues
                        .map((issue) =>
                          richTextToPlainText(issue.title ?? issue.name),
                        )
                        .filter(Boolean)
                        .join(", ") || "-"
                    : "-";

                return (
                  <TableRow
                    key={row.id}
                    hover
                    sx={{
                      "&:hover": {
                        bgcolor: alpha(
                          theme.palette.primary.main,
                          isDark ? 0.08 : 0.035,
                        ),
                      },
                    }}
                  >
                    <TableCell sx={bodyCellSx}>
                      {rowNumber}
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      <Stack
                        direction="row"
                        spacing={1.1}
                        sx={{
                          minWidth: 0,
                          alignItems: "center",
                        }}
                      >
                        <Avatar
                          src={
                            row.ministryLogo ||
                            undefined
                          }
                          alt={row.ministry}
                          sx={{
                            width: 26,
                            height: 26,
                            flexShrink: 0,
                            bgcolor:
                              theme.palette.background
                                .paper,
                            color:
                              theme.palette.primary.main,
                            border: `1px solid ${theme.palette.primary.main}`,
                            fontSize: 9,
                            fontWeight: 800,
                          }}
                        >
                          {row.ministry
                            .trim()
                            .charAt(0)
                            .toUpperCase()}
                        </Avatar>

                        <Typography
                          sx={{
                            minWidth: 0,
                            color:
                              theme.palette.text.primary,
                            fontSize: 13,
                            fontWeight: 600,
                            lineHeight: "16px",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                          }}
                        >
                          {row.ministry}
                        </Typography>
                      </Stack>
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      <Typography
                        sx={{
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                          fontSize: 13,
                          fontWeight: 500,
                          lineHeight: "16px",
                        }}
                        title={decisionText}
                      >
                        {decisionText}
                      </Typography>
                    </TableCell>

                    {/* 🔥 បន្ថែម TableCell សម្រាប់បង្ហាញ Issues */}
                    <TableCell sx={bodyCellSx}>
                      <Typography
                        sx={{
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                          fontSize: 13,
                          fontWeight: 500,
                          lineHeight: "16px",
                        }}
                      >
                        {issuesText}
                      </Typography>
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      {row.meetingDate || ""}
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      {row.category || ""}
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      <MinistryRgcDecisionStatusChip
                        status={row.status}
                      />
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      {row.focalPerson || ""}
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      <Typography
                        sx={{
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                          fontSize: 13,
                          fontWeight: 500,
                          lineHeight: "16px",
                        }}
                        title={verificationText}
                      >
                        {verificationText}
                      </Typography>
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      {row.verificationLink ? (
                        <Link
                          href={row.verificationLink}
                          target="_blank"
                          rel="noopener noreferrer"
                          underline="always"
                          onClick={(event) =>
                            event.stopPropagation()
                          }
                          sx={{
                            color:
                              theme.palette.primary.main,
                            fontSize: 13,
                            fontWeight: 500,
                            lineHeight: "16px",
                          }}
                        >
                          {text.download}
                        </Link>
                      ) : null}
                    </TableCell>

                    <TableCell sx={bodyCellSx}>
                      <Button
                        variant="text"
                        startIcon={
                          <RemoveRedEyeOutlinedIcon
                            sx={{ fontSize: 16 }}
                          />
                        }
                        disabled={!onViewDetail}
                        onClick={() =>
                          onViewDetail?.(row)
                        }
                        sx={{
                          minWidth: 0,
                          p: 0,
                          color:
                            theme.palette.text.secondary,
                          textTransform: "none",
                          fontSize: 13,
                          fontWeight: 500,
                          lineHeight: "16px",

                          "&:hover": {
                            bgcolor: "transparent",
                            color:
                              theme.palette.primary.main,
                          },
                        }}
                      >
                        {text.viewDetail}
                      </Button>
                    </TableCell>
                  </TableRow>
                );
              })}

            {!loading && rows.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={11}
                  sx={{
                    height: 120,
                    textAlign: "center",
                    color:
                      theme.palette.text.secondary,
                    borderColor:
                      theme.palette.divider,
                    fontSize: 13,
                  }}
                >
                  {text.noDecisions}
                </TableCell>
              </TableRow>
            ) : null}
          </TableBody>
        </Table>
      </TableContainer>

      <PaginationFooter
        currentPage={safeCurrentPage}
        totalPages={totalPages}
        onPageChange={handlePageChange}
      />
    </Paper>
  );
}

export default MinistryRgcDecisionTable;