"use client";

import {
  useEffect,
  useMemo,
  useState,
} from "react";
import { useParams } from "next/navigation";

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

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

const API_BASE_URL = (
  process.env.NEXT_PUBLIC_API_URL ??
  "http://localhost:3001/api/v1"
).replace(/\/$/, "");

const PAGE_SIZE = 10;
const API_FETCH_LIMIT = 100;

type ApiMessage =
  | string
  | string[]
  | undefined;

type PaginationItem =
  | number
  | "start-ellipsis"
  | "end-ellipsis";

type AuthUser = {
  id?: number | string;
  userId?: number | string;
};

type AuthMeResponse = {
  id?: number | string;
  userId?: number | string;
  user?: AuthUser;

  data?: {
    id?: number | string;
    userId?: number | string;
    user?: AuthUser;
  };

  message?: ApiMessage;
};

type ApiStakeholder = {
  id?: number;
  name?: string | null;
  logo?: string | null;
};

type ApiCategory = {
  id?: number;
  name?: string | null;
};

type ApiIndicator = {
  id?: number;
  name?: string | null;
  description?: string | null;
};

type ApiIssueItem = {
  id?: number | string;
  title?: string | null;
  name?: string | null;
  description?: string | null;
};

type ApiRgcDecision = {
  id?: number;
  plenaryId?: number | null;

  stakeholderId?: number;
  stakeholder?: ApiStakeholder | null;

  categoryId?: number;

  category?:
    | string
    | ApiCategory
    | null;

  categoryInfo?: ApiCategory | null;

  indicatorId?: number | null;
  indicator?: ApiIndicator | string | null;
  indicatorName?: string | null;
  indicatorDescription?: string | null;

  meetingDate?: string | null;

  status?: string | null;
  statusCode?: string | null;

  focalPerson?: string | null;
  decision?: string | null;

  verificationSource?: string | null;
  sourceOfVerification?: string | null;
  verificationLink?: string | null;

  issues?: ApiIssueItem[];

  createdAt?: string | null;
  updatedAt?: string | null;
};

type ApiMeta = {
  total?: number;
  page?: number;
  limit?: number;
  totalPages?: number;
};

type ApiListResponse = {
  success?: boolean;
  statusCode?: number;
  message?: ApiMessage;

  data?: {
    items?: ApiRgcDecision[];
    meta?: ApiMeta;
  };

  items?: ApiRgcDecision[];
  meta?: ApiMeta;
};

type RgcDecisionRow = {
  id: number;

  ministryName: string;
  ministryLogo: string | null;

  decision: string;
  meetingDate: string;
  category: string;
  status: RgcDecisionStatus;
  indicator: string;
  focalPerson: string;
  sourceOfVerification: string;
  verificationLink: string;
  issues?: ApiIssueItem[];
};

type RgcDecisionStatus =
  | "Not Addressed"
  | "In Progress"
  | "Solved";

type TableData = {
  items: RgcDecisionRow[];

  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
};

type PlenaryRgcDecisionTableProps = {
  plenaryId?: number | string;
  onViewDetail?: (
    row: RgcDecisionRow,
  ) => void;
};

function getPaginationItems(
  totalPages: number,
  currentPage: number,
): PaginationItem[] {
  if (totalPages <= 7) {
    return Array.from(
      {
        length: totalPages,
      },
      (_, index) => index + 1,
    );
  }

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

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

  return [
    1,
    "start-ellipsis",
    currentPage - 1,
    currentPage,
    currentPage + 1,
    "end-ellipsis",
    totalPages,
  ];
}

function getErrorMessage(
  message: ApiMessage,
): string {
  if (Array.isArray(message)) {
    return message.join(", ");
  }

  if (
    typeof message === "string" &&
    message.trim()
  ) {
    return message;
  }

  return "Unable to load RGC Decisions.";
}

function toValidUserId(
  value: unknown,
): string {
  if (
    typeof value !== "string" &&
    typeof value !== "number"
  ) {
    return "";
  }

  const id = Number(value);

  if (
    !Number.isInteger(id) ||
    id < 1
  ) {
    return "";
  }

  return String(id);
}

async function readJson<T>(
  response: Response,
): Promise<T> {
  const text = await response.text();

  if (!text) {
    return {} as T;
  }

  try {
    return JSON.parse(text) as T;
  } catch {
    return {} as T;
  }
}

function getStoredUserId(): string {
  if (typeof window === "undefined") {
    return "";
  }

  const directKeys = [
    "userId",
    "user_id",
    "currentUserId",
    "authUserId",
  ];

  for (const key of directKeys) {
    const userId = toValidUserId(
      window.localStorage.getItem(key),
    );

    if (userId) {
      return userId;
    }
  }

  const objectKeys = [
    "user",
    "authUser",
    "currentUser",
    "auth",
    "profile",
    "session",
  ];

  for (const key of objectKeys) {
    const rawValue =
      window.localStorage.getItem(key);

    if (!rawValue) {
      continue;
    }

    try {
      const parsed = JSON.parse(
        rawValue,
      ) as {
        id?: unknown;
        userId?: unknown;

        user?: {
          id?: unknown;
          userId?: unknown;
        };

        data?: {
          id?: unknown;
          userId?: unknown;

          user?: {
            id?: unknown;
            userId?: unknown;
          };
        };
      };

      const userId =
        toValidUserId(parsed.id) ||
        toValidUserId(parsed.userId) ||
        toValidUserId(
          parsed.user?.id,
        ) ||
        toValidUserId(
          parsed.user?.userId,
        ) ||
        toValidUserId(
          parsed.data?.id,
        ) ||
        toValidUserId(
          parsed.data?.userId,
        ) ||
        toValidUserId(
          parsed.data?.user?.id,
        ) ||
        toValidUserId(
          parsed.data?.user?.userId,
        );

      if (userId) {
        return userId;
      }
    } catch {
      // Ignore invalid localStorage data.
    }
  }

  return "";
}

async function getCurrentLoginUserId(): Promise<string> {
  try {
    const response = await fetch(
      `${API_BASE_URL}/auth/me`,
      {
        method: "GET",
        credentials: "include",
        cache: "no-store",
      },
    );

    const result =
      await readJson<AuthMeResponse>(
        response,
      );

    if (response.ok) {
      const userId =
        toValidUserId(
          result.data?.user?.id,
        ) ||
        toValidUserId(
          result.data?.user?.userId,
        ) ||
        toValidUserId(
          result.data?.id,
        ) ||
        toValidUserId(
          result.data?.userId,
        ) ||
        toValidUserId(
          result.user?.id,
        ) ||
        toValidUserId(
          result.user?.userId,
        ) ||
        toValidUserId(result.id) ||
        toValidUserId(
          result.userId,
        );

      if (userId) {
        return userId;
      }
    }
  } catch {
    // Use browser storage fallback.
  }

  const storedUserId =
    getStoredUserId();

  if (storedUserId) {
    return storedUserId;
  }

  throw new Error(
    "Login user ID not found. Please login again.",
  );
}

async function getHeaders(): Promise<HeadersInit> {
  const userId =
    await getCurrentLoginUserId();

  return {
    Accept: "application/json",
    "Content-Type": "application/json",
    "x-user-id": userId,
  };
}

function formatDate(
  value: string | null | undefined,
): string {
  if (!value) {
    return "-";
  }

  const text = String(value);

  if (
    /^\d{4}-\d{2}-\d{2}/.test(text)
  ) {
    return text.slice(0, 10);
  }

  const date = new Date(value);

  if (
    Number.isNaN(date.getTime())
  ) {
    return "-";
  }

  const year = date.getUTCFullYear();

  const month = String(
    date.getUTCMonth() + 1,
  ).padStart(2, "0");

  const day = String(
    date.getUTCDate(),
  ).padStart(2, "0");

  return `${year}-${month}-${day}`;
}

function stripHtml(
  value: string | null | undefined,
): string {
  if (!value) {
    return "-";
  }

  return value
    .replace(/<br\s*\/?>/gi, " ")
    .replace(/<\/p>/gi, " ")
    .replace(/<\/div>/gi, " ")
    .replace(/<[^>]*>/g, " ")
    .replace(/&nbsp;/gi, " ")
    .replace(/&amp;/gi, "&")
    .replace(/&lt;/gi, "<")
    .replace(/&gt;/gi, ">")
    .replace(/\s+/g, " ")
    .trim();
}

function getCategoryName(
  item: ApiRgcDecision,
): string {
  if (
    typeof item.category === "string" &&
    item.category.trim()
  ) {
    return item.category.trim();
  }

  if (
    typeof item.category === "object" &&
    item.category?.name?.trim()
  ) {
    return item.category.name.trim();
  }

  if (
    item.categoryInfo?.name?.trim()
  ) {
    return item.categoryInfo.name.trim();
  }

  return "-";
}

function getIndicatorName(
  item: ApiRgcDecision,
): string {
  if (
    typeof item.indicator === "string" &&
    item.indicator.trim()
  ) {
    return item.indicator.trim();
  }

  if (
    typeof item.indicator === "object" &&
    item.indicator?.name?.trim()
  ) {
    return item.indicator.name.trim();
  }

  if (item.indicatorName?.trim()) {
    return item.indicatorName.trim();
  }

  return "-";
}

function normalizeStatus(
  value: string | null | undefined,
): RgcDecisionStatus {
  const normalized = String(
    value ?? "",
  )
    .trim()
    .toUpperCase()
    .replace(/[\s-]+/g, "_");

  if (
    normalized === "SOLVED"
  ) {
    return "Solved";
  }

  if (
    normalized === "IN_PROGRESS"
  ) {
    return "In Progress";
  }

  return "Not Addressed";
}

function mapRgcDecision(
  item: ApiRgcDecision,
): RgcDecisionRow {
  return {
    id: Number(item.id ?? 0),

    ministryName:
      item.stakeholder?.name?.trim() ||
      "-",

    ministryLogo:
      item.stakeholder?.logo?.trim() ||
      null,

    decision:
      stripHtml(item.decision),

    meetingDate:
      formatDate(item.meetingDate),

    category:
      getCategoryName(item),

    status:
      normalizeStatus(
        item.statusCode ??
          item.status,
      ),

    indicator:
      getIndicatorName(item),

    focalPerson:
      item.focalPerson?.trim() ||
      "-",

    sourceOfVerification:
      stripHtml(
        item.sourceOfVerification ??
          item.verificationSource,
      ),

    verificationLink:
      item.verificationLink?.trim() ||
      "",

    issues: item.issues ?? [],
  };
}

async function getPlenaryRgcDecisions(
  plenaryId: number,
  page: number,
): Promise<TableData> {
  const params = new URLSearchParams({
    plenaryId: String(plenaryId),
    page: "1",
    limit: String(API_FETCH_LIMIT),
  });

  const response = await fetch(
    `${API_BASE_URL}/rgc-decisions?${params.toString()}`,
    {
      method: "GET",
      headers: await getHeaders(),
      credentials: "include",
      cache: "no-store",
    },
  );

  const result =
    await readJson<ApiListResponse>(
      response,
    );

  if (!response.ok) {
    throw new Error(
      getErrorMessage(
        result.message,
      ),
    );
  }

  const rawItems =
    result.data?.items ??
    result.items ??
    [];

  const plenaryItems =
    rawItems.filter(
      (item) =>
        Number(item.plenaryId) ===
        plenaryId,
    );

  const total =
    plenaryItems.length;

  const totalPages = Math.max(
    1,
    Math.ceil(total / PAGE_SIZE),
  );

  const safePage = Math.min(
    Math.max(1, page),
    totalPages,
  );

  const pageItems =
    plenaryItems.slice(
      (safePage - 1) * PAGE_SIZE,
      safePage * PAGE_SIZE,
    );

  return {
    items:
      pageItems.map(
        mapRgcDecision,
      ),

    meta: {
      total,
      page: safePage,
      limit: PAGE_SIZE,
      totalPages,
    },
  };
}

function MinistryCell({
  name,
  logo,
}: {
  name: string;
  logo: string | null;
}) {
  const theme = useTheme();

  const firstLetter =
    name
      .trim()
      .charAt(0)
      .toUpperCase() || "M";

  return (
    <Stack
      direction="row"
      spacing={1.15}
      sx={{
        minWidth: 0,
        alignItems: "center",
      }}
    >
      {logo ? (
        <Avatar
          src={logo}
          alt={name}
          sx={{
            width: 30,
            height: 30,
            flexShrink: 0,
            border:
              "1px solid",
            borderColor:
              "divider",
          }}
        />
      ) : (
        <Avatar
          sx={{
            width: 30,
            height: 30,
            flexShrink: 0,

            color:
              theme.palette.primary.main,

            bgcolor: alpha(
              theme.palette.primary.main,
              0.13,
            ),

            border: `1px solid ${alpha(
              theme.palette.primary.main,
              0.35,
            )}`,

            fontSize: 11,
            fontWeight: 800,
          }}
        >
          {firstLetter}
        </Avatar>
      )}

      <Typography
        title={name}
        sx={{
          minWidth: 0,
          overflow: "hidden",
          color:
            theme.palette.text.primary,
          fontSize: 13,
          fontWeight: 700,
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}
      >
        {name}
      </Typography>
    </Stack>
  );
}

function StatusChip({
  status,
}: {
  status: RgcDecisionStatus;
}) {
  const theme = useTheme();
  const isDark =
    theme.palette.mode === "dark";

  const style =
    status === "Solved"
      ? {
          color: "#16A34A",
          border: "#86EFAC",
          background: "#F0FDF4",
        }
      : status === "In Progress"
        ? {
            color: "#F59E0B",
            border: "#FCD34D",
            background: "#FFFBEB",
          }
        : {
            color: "#EF4444",
            border: "#FCA5A5",
            background: "#FEF2F2",
          };

  return (
    <Box
      sx={{
        minWidth: 100,
        height: 22,

        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",

        px: 1.3,

        border: `1px solid ${style.border}`,
        borderRadius: 99,

        color: style.color,

        bgcolor: isDark
          ? alpha(
              style.color,
              0.16,
            )
          : style.background,

        fontSize: 11,
        fontWeight: 700,
        whiteSpace: "nowrap",
      }}
    >
      {status}
    </Box>
  );
}

function EllipsisText({
  children,
}: {
  children: React.ReactNode;
}) {
  const theme = useTheme();
  return (
    <Box
      sx={{
        width: "100%",
        color: theme.palette.text.primary,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </Box>
  );
}

export function PlenaryRgcDecisionTable({
  plenaryId,
  onViewDetail,
}: PlenaryRgcDecisionTableProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const params = useParams<{
    id?: string | string[];
  }>();

  const routeId =
    Array.isArray(params?.id)
      ? params.id[0]
      : params?.id;

  const resolvedPlenaryId =
    useMemo(() => {
      const parsedId = Number(
        plenaryId ?? routeId,
      );

      if (
        !Number.isInteger(
          parsedId,
        ) ||
        parsedId < 1
      ) {
        return 0;
      }

      return parsedId;
    }, [plenaryId, routeId]);

  const isValidPlenaryId =
    resolvedPlenaryId > 0;

  const [paginationState, setPaginationState] =
    useState<{
      plenaryId: number;
      page: number;
    }>({
      plenaryId: resolvedPlenaryId,
      page: 1,
    });

  const page =
    paginationState.plenaryId === resolvedPlenaryId
      ? paginationState.page
      : 1;

  const [loading, setLoading] =
    useState(true);

  const [error, setError] =
    useState<string | null>(
      null,
    );

  const [
    tableData,
    setTableData,
  ] = useState<TableData>({
    items: [],

    meta: {
      total: 0,
      page: 1,
      limit: PAGE_SIZE,
      totalPages: 1,
    },
  });

  useEffect(() => {
    if (!isValidPlenaryId) {
      return;
    }

    let cancelled = false;

    async function loadRgcDecisions() {
      try {
        setLoading(true);

        const result =
          await getPlenaryRgcDecisions(
            resolvedPlenaryId,
            page,
          );

        if (cancelled) {
          return;
        }

        setTableData(result);
        setError(null);
      } catch (requestError) {
        if (cancelled) {
          return;
        }

        setError(
          requestError instanceof Error
            ? requestError.message
            : "Unable to load RGC Decisions.",
        );
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }

    void loadRgcDecisions();

    return () => {
      cancelled = true;
    };
  }, [
    isValidPlenaryId,
    page,
    resolvedPlenaryId,
  ]);

  const effectiveLoading =
    isValidPlenaryId && loading;

  const displayError =
    isValidPlenaryId
      ? error
      : "Invalid Plenary ID.";

  const currentPage =
    tableData.meta.page;

  const totalPages =
    tableData.meta.totalPages;

  const paginationItems =
    useMemo(
      () =>
        getPaginationItems(
          totalPages,
          currentPage,
        ),
      [
        currentPage,
        totalPages,
      ],
    );

  const changePage = (
    nextPage: number,
  ) => {
    if (
      !isValidPlenaryId ||
      effectiveLoading ||
      nextPage < 1 ||
      nextPage >
        totalPages ||
      nextPage ===
        currentPage
    ) {
      return;
    }

    setPaginationState({
      plenaryId: resolvedPlenaryId,
      page: nextPage,
    });
  };

  const headerBackground =
    theme.palette.mode ===
    "dark"
      ? alpha(
          theme.palette.primary.main,
          0.18,
        )
      : "#DCEEFF";

  const borderColor =
    theme.palette.mode ===
    "dark"
      ? alpha(
          "#FFFFFF",
          0.12,
        )
      : "#E3EAF2";

  const headerCellSx = {
    height: 54,
    px: 2,
    py: 0,

    color:
      theme.palette.text.secondary,

    bgcolor:
      headerBackground,

    borderColor,

    fontSize: 13,
    fontWeight: 600,
    whiteSpace: "nowrap",
  };

  const bodyCellSx = {
    height: 64,
    px: 2,
    py: 0,

    color:
      theme.palette.text.primary,

    borderColor,

    fontSize: 13,
    fontWeight: 500,

    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  };

  // 🌟 Styling ថ្មីសម្រាប់ Button Previous និង Next ឱ្យត្រូវតាម UI Design Standard
  const navButtonSx = {
    height: 36,
    minWidth: 104,
    px: 1.3,
    borderRadius: "8px",
    textTransform: "none",
    color: theme.palette.text.primary,
    borderColor: theme.palette.divider,
    fontSize: 12,
    fontWeight: 600,
    bgcolor: theme.palette.background.paper,
    boxShadow: "none",

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

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

  return (
    <Box sx={{ mt: 3 }}>
      <Typography
        sx={{
          mb: 1.5,
          color:
            theme.palette.text.primary,
          fontSize: 16,
          fontWeight: 700,
        }}
      >
        List of RGC Decisions
      </Typography>

      {displayError ? (
        <Alert
          severity="error"
          sx={{ mb: 1.5 }}
        >
          {displayError}
        </Alert>
      ) : null}

      <Paper
        elevation={0}
        sx={{
          width: "100%",
          maxWidth: "100%",

          overflow: "hidden",

          border: "1px solid",
          borderColor,
          borderRadius: 2,

          bgcolor:
            theme.palette.background.paper,
        }}
      >
        <TableContainer
          sx={{
            width: "100%",
            maxWidth: "100%",

            overflowX: "auto",
            overflowY: "hidden",

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

            "&::-webkit-scrollbar-track": {
              bgcolor:
                theme.palette.mode ===
                "dark"
                  ? alpha(
                      "#FFFFFF",
                      0.08,
                    )
                  : "#EEF2F6",
            },

            "&::-webkit-scrollbar-thumb": {
              bgcolor:
                theme.palette.mode ===
                "dark"
                  ? alpha(
                      "#FFFFFF",
                      0.28,
                    )
                  : "#CBD5E1",

              borderRadius: 99,
            },

            "&::-webkit-scrollbar-thumb:hover": {
              bgcolor:
                theme.palette.mode ===
                "dark"
                  ? alpha(
                      "#FFFFFF",
                      0.4,
                    )
                  : "#94A3B8",
            },
          }}
        >
          <Table
            size="small"
            sx={{
              minWidth: 2600,
              tableLayout: "fixed",
            }}
          >
            <TableHead>
              <TableRow>
                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 70,
                  }}
                >
                  No
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 190,
                  }}
                >
                  Ministry
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 400,
                  }}
                >
                  RGC&apos;s Decision
                </TableCell>

                {/* 🔥 Column Linked Issues (សរុប Table មាន 12 Columns) */}
                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 280,
                  }}
                >
                  Linked Issues
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 150,
                  }}
                >
                  Meeting Date
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 160,
                  }}
                >
                  Category
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 180,
                  }}
                >
                  Status
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 140,
                  }}
                >
                  Indicator
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 160,
                  }}
                >
                  Focal Person (H.E)
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 190,
                  }}
                >
                  Source of Verification
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 190,
                  }}
                >
                  Link to Verification Source
                </TableCell>

                <TableCell
                  sx={{
                    ...headerCellSx,
                    width: 140,
                  }}
                >
                  Action
                </TableCell>
              </TableRow>
            </TableHead>

            <TableBody>
              {effectiveLoading ? (
                <TableRow>
                  <TableCell
                    colSpan={12}
                    sx={{
                      height: 220,
                      borderColor,
                    }}
                  >
                    <Stack
                      spacing={1.25}
                      sx={{
                        alignItems:
                          "center",
                        justifyContent:
                          "center",
                      }}
                    >
                      <CircularProgress
                        size={28}
                      />

                      <Typography
                        sx={{
                          color:
                            theme.palette
                              .text
                              .secondary,
                          fontSize: 13,
                        }}
                      >
                        Loading RGC
                        Decisions...
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : null}

              {!effectiveLoading &&
              !displayError &&
              tableData.items
                .length === 0 ? (
                <TableRow>
                  <TableCell
                    colSpan={12}
                    sx={{
                      height: 145,
                      borderColor,
                      textAlign:
                        "center",
                    }}
                  >
                    <Typography
                      sx={{
                        color:
                          theme.palette
                            .text
                            .secondary,
                        fontSize: 13,
                      }}
                    >
                      No RGC Decision
                      found.
                    </Typography>
                  </TableCell>
                </TableRow>
              ) : null}

              {!effectiveLoading &&
                tableData.items.map(
                  (row, index) => {
                    const rowNumber =
                      (currentPage -
                        1) *
                        tableData.meta
                          .limit +
                      index +
                      1;

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

                    return (
                      <TableRow
                        key={row.id}
                        hover
                        sx={{
                          bgcolor:
                            theme.palette
                              .background
                              .paper,

                          "&:hover": {
                            bgcolor:
                              alpha(
                                theme
                                  .palette
                                  .primary
                                  .main,
                                isDark
                                  ? 0.1
                                  : 0.04,
                              ),
                          },
                        }}
                      >
                        <TableCell
                          sx={bodyCellSx}
                        >
                          {rowNumber}
                        </TableCell>

                        <TableCell
                          sx={bodyCellSx}
                        >
                          <MinistryCell
                            name={
                              row.ministryName
                            }
                            logo={
                              row.ministryLogo
                            }
                          />
                        </TableCell>

                        <TableCell
                          sx={bodyCellSx}
                        >
                          <EllipsisText>
                            {
                              row.decision
                            }
                          </EllipsisText>
                        </TableCell>

                        {/* 🔥 TableCell សម្រាប់បង្ហាញ Linked Issues */}
                        <TableCell
                          sx={bodyCellSx}
                        >
                          <EllipsisText>
                            {issuesText}
                          </EllipsisText>
                        </TableCell>

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

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

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

                        <TableCell
                          sx={bodyCellSx}
                        >
                          {row.indicator}
                        </TableCell>

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

                        <TableCell
                          sx={bodyCellSx}
                        >
                          <EllipsisText>
                            {
                              row.sourceOfVerification
                            }
                          </EllipsisText>
                        </TableCell>

                        <TableCell
                          sx={bodyCellSx}
                        >
                          {row.verificationLink ? (
                            <Link
                              href={
                                row.verificationLink
                              }
                              target="_blank"
                              rel="noopener noreferrer"
                              underline="always"
                              title={
                                row.verificationLink
                              }
                              sx={{
                                display:
                                  "block",
                                overflow:
                                  "hidden",
                                color:
                                  theme
                                    .palette
                                    .primary
                                    .main,
                                fontSize: 13,
                                fontWeight: 700,
                                textOverflow:
                                  "ellipsis",
                                whiteSpace:
                                  "nowrap",
                              }}
                            >
                              View Source
                            </Link>
                          ) : (
                            "-"
                          )}
                        </TableCell>

                        <TableCell
                          sx={{
                            ...bodyCellSx,
                            overflow:
                              "visible",
                          }}
                        >
                          <Button
                            variant="text"
                            size="small"
                            startIcon={
                              <RemoveRedEyeOutlinedIcon
                                sx={{
                                  fontSize: 16,
                                }}
                              />
                            }
                            onClick={() =>
                              onViewDetail?.(
                                row,
                              )
                            }
                            sx={{
                              textTransform:
                                "none",
                              fontWeight: 600,
                            }}
                          >
                            View Detail
                          </Button>
                        </TableCell>
                      </TableRow>
                    );
                  },
                )}
            </TableBody>
          </Table>
        </TableContainer>

        {/* 🌟 Footer UI Pagination ថ្មី (ស្ដង់ដារស្អាតដូចរូបភាពចង់បាន) */}
        <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: 110,
              },
              display: "flex",
              justifyContent: {
                xs: "center",
                sm: "flex-start",
              },
            }}
          >
            <Button
              variant="outlined"
              disabled={
                !isValidPlenaryId ||
                effectiveLoading ||
                currentPage <= 1
              }
              startIcon={
                <ArrowBackRoundedIcon
                  sx={{ fontSize: 16 }}
                />
              }
              onClick={() =>
                changePage(
                  currentPage - 1,
                )
              }
              sx={navButtonSx}
            >
              Previous
            </Button>
          </Box>

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

                const active =
                  item === currentPage;

                return (
                  <Button
                    key={item}
                    variant="text"
                    disabled={
                      effectiveLoading
                    }
                    onClick={() =>
                      changePage(
                        Number(item),
                      )
                    }
                    sx={{
                      minWidth: 36,
                      width: 36,
                      height: 36,
                      p: 0,
                      borderRadius:
                        "8px",
                      textTransform:
                        "none",
                      color: active
                        ? theme
                            .palette
                            .primary
                            .contrastText
                        : theme
                            .palette
                            .text
                            .secondary,
                      bgcolor: active
                        ? theme
                            .palette
                            .primary
                            .main
                        : "transparent",
                      fontSize: 12,
                      fontWeight: active
                        ? 700
                        : 500,

                      "&:hover": {
                        bgcolor:
                          active
                            ? theme
                                .palette
                                .primary
                                .dark
                            : alpha(
                                theme
                                  .palette
                                  .primary
                                  .main,
                                isDark
                                  ? 0.14
                                  : 0.08,
                              ),
                      },
                    }}
                  >
                    {item}
                  </Button>
                );
              },
            )}
          </Stack>

          <Box
            sx={{
              width: {
                xs: "100%",
                sm: 110,
              },
              display: "flex",
              justifyContent: {
                xs: "center",
                sm: "flex-end",
              },
            }}
          >
            <Button
              variant="outlined"
              disabled={
                !isValidPlenaryId ||
                effectiveLoading ||
                currentPage >=
                  totalPages
              }
              endIcon={
                <ArrowForwardRoundedIcon
                  sx={{ fontSize: 16 }}
                />
              }
              onClick={() =>
                changePage(
                  currentPage + 1,
                )
              }
              sx={navButtonSx}
            >
              Next
            </Button>
          </Box>
        </Stack>
      </Paper>
    </Box>
  );
}

export const PlenaryRgcDecisionsTable =
  PlenaryRgcDecisionTable;

export default PlenaryRgcDecisionTable;