"use client";

import {
    useMemo,
    useState,
    type MouseEvent,
    type ReactNode,
} from "react";

import KeyboardArrowDownRoundedIcon from "@mui/icons-material/KeyboardArrowDownRounded";
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";

import Alert from "@mui/material/Alert";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import Checkbox from "@mui/material/Checkbox";
import CircularProgress from "@mui/material/CircularProgress";
import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Pagination from "@mui/material/Pagination";
import Paper from "@mui/material/Paper";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import type {
    CefpIssueMatrixRow,
    CefpIssueMatrixStatus,
} from "./cefp-issue-matrix-data";

import type {
    CefpIssueMatrixLanguage,
    CefpPlenaryEscalationControl,
    CefpStatusEditControl,
    CefpStatusOption,
} from "./cefp-issue-matrix-table";

const PAGE_SIZE = 8;
const LEFT_META_LABEL_WIDTH = 105;
const RIGHT_META_LABEL_WIDTH = 150;
const LEADING_SLOT_WIDTH = 28;

type CefpIssueMatrixGridProps = {
    rows: CefpIssueMatrixRow[];
    language: CefpIssueMatrixLanguage;

    loading?: boolean;
    error?: string | null;
    showRemark?: boolean;

    plenaryEscalationControl?: CefpPlenaryEscalationControl;
    statusEditControl?: CefpStatusEditControl;

    onView?: (row: CefpIssueMatrixRow) => void;
    onEdit?: (row: CefpIssueMatrixRow) => void;
    onRemove?: (row: CefpIssueMatrixRow) => void;
};

type GridText = {
    noData: string;
    number: string;
    workingGroup: string;
    ministry: string;
    category: string;
    issue: string;
    escalation: string;
    status: string;
    description: string;
    recommendation: string;
    rgcDecision: string;
    nextStep: string;
    remark: string;
    action: string;
    edit: string;
    remove: string;
    yes: string;
    no: string;
};

const GRID_TEXT: Record<CefpIssueMatrixLanguage, GridText> = {
    en: {
        noData: "No issue data available.",
        number: "No.",
        workingGroup: "Working Group Name",
        ministry: "Ministry",
        category: "Category of Issue",
        issue: "Issue",
        escalation: "Plenary Escalation",
        status: "Status",
        description: "Issue Description",
        recommendation: "Recommendation",
        rgcDecision: "RGC Decision",
        nextStep: "Next Step",
        remark: "Remark",
        action: "Action",
        edit: "Edit",
        remove: "Remove",
        yes: "Yes",
        no: "No",
    },

    kh: {
        noData: "មិនមានទិន្នន័យបញ្ហា។",
        number: "ល.រ",
        workingGroup: "ឈ្មោះក្រុមការងារ",
        ministry: "ក្រសួង/ស្ថាប័ន",
        category: "ប្រភេទបញ្ហា",
        issue: "បញ្ហា",
        escalation: "បញ្ជូនទៅកិច្ចប្រជុំពេញអង្គ",
        status: "ស្ថានភាព",
        description: "ការពិពណ៌នាបញ្ហា",
        recommendation: "អនុសាសន៍",
        rgcDecision: "សេចក្តីសម្រេច RGC",
        nextStep: "ជំហានបន្ទាប់",
        remark: "កំណត់សម្គាល់",
        action: "សកម្មភាព",
        edit: "កែប្រែ",
        remove: "លុប",
        yes: "បាទ/ចាស",
        no: "ទេ",
    },
};

function getFontFamily(language: CefpIssueMatrixLanguage): string {
    return language === "kh"
        ? '"Battambang", "Kantumruy Pro", sans-serif'
        : '"Inter", "Segoe UI", Arial, sans-serif';
}

function normalizeText(value: unknown): string {
    if (value === null || value === undefined) {
        return "-";
    }

    if (typeof value === "string") {
        return value.trim() || "-";
    }

    if (typeof value === "number" || typeof value === "boolean") {
        return String(value);
    }

    return "-";
}

function getInitials(name: string): string {
    const parts = name.trim().split(/\s+/).filter(Boolean);

    if (parts.length === 0) {
        return "?";
    }

    if (parts.length === 1) {
        return parts[0].slice(0, 2).toUpperCase();
    }

    return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
}

function isMinistrySubmittedIssue(
    row: CefpIssueMatrixRow,
): boolean {
    /*
     * Do not change the old CefpIssueMatrixRow type.
     * Ministry-shared issues already carry meetingSummaryId.
     */
    return (
        typeof row.meetingSummaryId === "number" &&
        row.meetingSummaryId > 0
    );
}

function getStatusStyles(status: CefpIssueMatrixStatus) {
    switch (status) {
        case "In Progress":
            return {
                color: "#F59E0B",
                dotColor: "#F59E0B",
                borderColor: "rgba(245, 158, 11, 0.32)",
                backgroundColor: "rgba(245, 158, 11, 0.08)",
            };

        case "Solved":
            return {
                color: "#22C55E",
                dotColor: "#22C55E",
                borderColor: "rgba(34, 197, 94, 0.30)",
                backgroundColor: "rgba(34, 197, 94, 0.08)",
            };

        case "Not Addressed":
            return {
                color: "#EF4444",
                dotColor: "#EF4444",
                borderColor: "rgba(239, 68, 68, 0.30)",
                backgroundColor: "rgba(239, 68, 68, 0.08)",
            };

        case "Saved":
            return {
                color: "#3B82F6",
                dotColor: "#3B82F6",
                borderColor: "rgba(59, 130, 246, 0.30)",
                backgroundColor: "rgba(59, 130, 246, 0.08)",
            };

        case "Draft":
        default:
            return {
                color: "#94A3B8",
                dotColor: "#94A3B8",
                borderColor: "rgba(148, 163, 184, 0.24)",
                backgroundColor: "rgba(148, 163, 184, 0.06)",
            };
    }
}

function GridLabel({
    children,
    language,
}: {
    children: ReactNode;
    language: CefpIssueMatrixLanguage;
}) {
    const theme = useTheme();

    return (
        <Typography
            sx={{
                color:
                    theme.palette.mode === "dark"
                        ? alpha("#FFFFFF", 0.62)
                        : "#717680",
                fontFamily: getFontFamily(language),
                fontSize: 12,
                fontWeight: 500,
                whiteSpace: "nowrap",
            }}
        >
            {children}
        </Typography>
    );
}

function GridValueText({
    children,
    language,
    clamp = false,
    wrap = false,
}: {
    children: ReactNode;
    language: CefpIssueMatrixLanguage;
    clamp?: boolean;
    wrap?: boolean;
}) {
    return (
        <Typography
            sx={{
                color: "text.primary",
                fontFamily: getFontFamily(language),
                fontSize: 12.5,
                fontWeight: 500,
                lineHeight: 1.55,

                ...(wrap
                    ? {
                        whiteSpace: "normal",
                        overflowWrap: "anywhere",
                    }
                    : {
                        whiteSpace: "nowrap",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                    }),

                ...(clamp
                    ? {
                        display: "-webkit-box",
                        WebkitBoxOrient: "vertical",
                        WebkitLineClamp: 4,
                        overflow: "hidden",
                        whiteSpace: "normal",
                    }
                    : {}),
            }}
        >
            {children}
        </Typography>
    );
}

function GridMetaRow({
    label,
    labelWidth,
    children,
    language,
}: {
    label: string;
    labelWidth: number;
    children: ReactNode;
    language: CefpIssueMatrixLanguage;
}) {
    return (
        <Box
            sx={{
                display: "grid",
                gridTemplateColumns: `${labelWidth}px minmax(0, 1fr)`,
                alignItems: "center",
                columnGap: 1.5,
                minHeight: 30,
                minWidth: 0,
            }}
        >
            <GridLabel language={language}>{label}</GridLabel>
            <Box sx={{ minWidth: 0 }}>{children}</Box>
        </Box>
    );
}

function GridValueSlot({
    children,
    leading,
}: {
    children: ReactNode;
    leading?: ReactNode;
}) {
    if (!leading) {
        return <Box sx={{ minWidth: 0 }}>{children}</Box>;
    }

    return (
        <Box
            sx={{
                display: "grid",
                gridTemplateColumns: `${LEADING_SLOT_WIDTH}px minmax(0, 1fr)`,
                columnGap: 1.25,
                alignItems: "center",
                minWidth: 0,
            }}
        >
            <Box
                sx={{
                    width: LEADING_SLOT_WIDTH,
                    height: LEADING_SLOT_WIDTH,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                }}
            >
                {leading}
            </Box>

            <Box sx={{ minWidth: 0 }}>{children}</Box>
        </Box>
    );
}

function GridContentBlock({
    label,
    value,
    language,
}: {
    label: string;
    value: unknown;
    language: CefpIssueMatrixLanguage;
}) {
    return (
        <Box sx={{ minWidth: 0 }}>
            <GridLabel language={language}>{label}</GridLabel>

            <Box sx={{ mt: 0.75 }}>
                <GridValueText language={language} clamp>
                    {normalizeText(value)}
                </GridValueText>
            </Box>
        </Box>
    );
}

function MinistryAvatar({
    row,
    language,
}: {
    row: CefpIssueMatrixRow;
    language: CefpIssueMatrixLanguage;
}) {
    const name = normalizeText(row.primaryAgency);

    return (
        <Avatar
            src={row.primaryAgencyImage || undefined}
            alt={name}
            sx={{
                width: LEADING_SLOT_WIDTH,
                height: LEADING_SLOT_WIDTH,
                border: "1px solid",
                borderColor: "divider",
                bgcolor: "action.hover",
                color: "primary.main",
                fontFamily: getFontFamily(language),
                fontSize: 8,
                fontWeight: 700,
            }}
        >
            {getInitials(name)}
        </Avatar>
    );
}

function GridEscalationControl({
    row,
    language,
    control,
}: {
    row: CefpIssueMatrixRow;
    language: CefpIssueMatrixLanguage;
    control?: CefpPlenaryEscalationControl;
}) {
    const text = GRID_TEXT[language];
    const isUpdating = control?.updatingIssueId === row.issueId;
    const canChange =
        !isMinistrySubmittedIssue(row) &&
        typeof control?.onChange === "function";

    if (isUpdating) {
        return <CircularProgress size={18} />;
    }

    return (
        <Box
            sx={{
                display: "flex",
                alignItems: "center",
                gap: 0.75,
                minWidth: 0,
            }}
        >
            <Checkbox
                size="small"
                checked={row.plenaryEscalation === true}
                disabled={!canChange}
                onChange={(event) => {
                    void control?.onChange?.(
                        row.issueId,
                        event.target.checked,
                    );
                }}
                sx={{
                    width: 24,
                    height: 24,
                    p: 0,
                    color: "text.disabled",

                    "&.Mui-checked": {
                        color: "primary.main",
                    },
                }}
            />

            <GridValueText language={language}>
                {row.plenaryEscalation ? text.yes : text.no}
            </GridValueText>
        </Box>
    );
}

function GridStatusControl({
    row,
    language,
    control,
}: {
    row: CefpIssueMatrixRow;
    language: CefpIssueMatrixLanguage;
    control?: CefpStatusEditControl;
}) {
    const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

    const options = useMemo(() => {
        const seen = new Set<string>();

        return (control?.options ?? []).filter((option) => {
            const key = option.name.trim().toLowerCase();

            if (seen.has(key)) {
                return false;
            }

            seen.add(key);
            return true;
        });
    }, [control?.options]);

    const isUpdating = control?.updatingIssueId === row.issueId;
    const canEdit =
        !isMinistrySubmittedIssue(row) &&
        typeof control?.onChange === "function" &&
        options.length > 0;

    const styles = getStatusStyles(row.status);
    const open = Boolean(anchorEl);

    const handleOpen = (event: MouseEvent<HTMLElement>) => {
        event.stopPropagation();

        if (!canEdit || isUpdating) {
            return;
        }

        setAnchorEl(event.currentTarget);
    };

    const handleSelect = async (option: CefpStatusOption) => {
        setAnchorEl(null);

        if (!control?.onChange) {
            return;
        }

        if (
            option.name === row.status &&
            option.id === row.statusId
        ) {
            return;
        }

        await control.onChange(row.issueId, option);
    };

    return (
        <>
            <ButtonBase
                type="button"
                disabled={!canEdit || isUpdating}
                onClick={handleOpen}
                sx={{
                    width: 160,
                    maxWidth: "100%",
                    height: 32,
                    px: 1.25,

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

                    border: "1px solid",
                    borderColor: styles.borderColor,
                    borderRadius: 999,

                    bgcolor: styles.backgroundColor,
                    color: styles.color,

                    fontFamily: getFontFamily(language),
                    fontSize: 12,
                    fontWeight: 500,
                    lineHeight: 1,

                    appearance: "none",
                    outline: "none",
                    cursor: canEdit ? "pointer" : "default",

                    "&:disabled": {
                        opacity: 1,
                        color: styles.color,
                        WebkitTextFillColor: styles.color,
                    },
                }}
            >
                {isUpdating ? (
                    <CircularProgress
                        size={14}
                        thickness={5}
                        color="inherit"
                    />
                ) : null}

                <Box
                    component="span"
                    sx={{
                        minWidth: 0,
                        flex: 1,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                    }}
                >
                    {row.status}
                </Box>

                {canEdit && !isUpdating ? (
                    <KeyboardArrowDownRoundedIcon
                        sx={{
                            width: 18,
                            height: 18,
                            flexShrink: 0,
                            transform: open ? "rotate(180deg)" : "none",
                        }}
                    />
                ) : null}
            </ButtonBase>

            <Menu
                anchorEl={anchorEl}
                open={open}
                onClose={() => setAnchorEl(null)}
                anchorOrigin={{
                    vertical: "bottom",
                    horizontal: "left",
                }}
                transformOrigin={{
                    vertical: "top",
                    horizontal: "left",
                }}
                slotProps={{
                    paper: {
                        sx: {
                            mt: 0.75,
                            minWidth: 180,
                            border: "1px solid",
                            borderColor: "divider",
                            borderRadius: 1.5,
                            bgcolor: "background.paper",
                            backgroundImage: "none",
                            boxShadow: "0 12px 28px rgba(15, 23, 42, 0.18)",
                        },
                    },

                    list: {
                        sx: {
                            p: 1,
                        },
                    },
                }}
            >
                {options.map((option) => {
                    const optionStyles = getStatusStyles(option.name);

                    return (
                        <MenuItem
                            key={`${option.id}-${option.name}`}
                            selected={option.name === row.status}
                            onClick={() => {
                                void handleSelect(option);
                            }}
                            sx={{
                                minHeight: 44,
                                px: 1.25,
                                py: 0.75,
                                gap: 1,
                                borderRadius: 1,
                                fontFamily: getFontFamily(language),

                                "&.Mui-selected": {
                                    bgcolor: "action.selected",
                                },

                                "&.Mui-selected:hover": {
                                    bgcolor: "action.selected",
                                },
                            }}
                        >
                            <Box
                                sx={{
                                    width: 9,
                                    height: 9,
                                    flexShrink: 0,
                                    borderRadius: "50%",
                                    bgcolor: optionStyles.dotColor,
                                }}
                            />

                            <Typography
                                sx={{
                                    color: optionStyles.color,
                                    fontFamily: getFontFamily(language),
                                    fontSize: 13,
                                    fontWeight: 500,
                                }}
                            >
                                {option.name}
                            </Typography>
                        </MenuItem>
                    );
                })}
            </Menu>
        </>
    );
}

function GridActionMenu({
    row,
    language,
    onView,
    onEdit,
    onRemove,
}: {
    row: CefpIssueMatrixRow;
    language: CefpIssueMatrixLanguage;
    onView?: (row: CefpIssueMatrixRow) => void;
    onEdit?: (row: CefpIssueMatrixRow) => void;
    onRemove?: (row: CefpIssueMatrixRow) => void;
}) {
    const text = GRID_TEXT[language];
    const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

    const ministryOnly =
        isMinistrySubmittedIssue(row);

    const hasAction =
        Boolean(onView) ||
        (!ministryOnly && Boolean(onEdit)) ||
        (!ministryOnly && Boolean(onRemove));

    return (
        <>
            <Tooltip title={text.action} arrow>
                <span>
                    <IconButton
                        size="small"
                        disabled={!hasAction}
                        onClick={(event) => {
                            event.stopPropagation();
                            setAnchorEl(event.currentTarget);
                        }}
                        sx={{
                            width: 32,
                            height: 32,
                            color: "text.secondary",
                        }}
                    >
                        <MoreVertRoundedIcon fontSize="small" />
                    </IconButton>
                </span>
            </Tooltip>

            <Menu
                anchorEl={anchorEl}
                open={Boolean(anchorEl)}
                onClose={() => setAnchorEl(null)}
                slotProps={{
                    paper: {
                        sx: {
                            minWidth: 150,
                            border: "1px solid",
                            borderColor: "divider",
                            borderRadius: 1.5,
                            bgcolor: "background.paper",
                            backgroundImage: "none",
                        },
                    },
                }}
            >
                {onView ? (
                    <MenuItem
                        onClick={() => {
                            setAnchorEl(null);
                            onView(row);
                        }}
                        sx={{
                            fontFamily: getFontFamily(language),
                            fontSize: 13,
                        }}
                    >
                        {language === "kh" ? "មើលលម្អិត" : "View Detail"}
                    </MenuItem>
                ) : null}

                {!ministryOnly && onEdit ? (
                    <MenuItem
                        onClick={() => {
                            setAnchorEl(null);
                            onEdit(row);
                        }}
                        sx={{
                            fontFamily: getFontFamily(language),
                            fontSize: 13,
                        }}
                    >
                        {text.edit}
                    </MenuItem>
                ) : null}

                {!ministryOnly && onRemove ? (
                    <MenuItem
                        onClick={() => {
                            setAnchorEl(null);
                            onRemove(row);
                        }}
                        sx={{
                            color: "error.main",
                            fontFamily: getFontFamily(language),
                            fontSize: 13,
                        }}
                    >
                        {text.remove}
                    </MenuItem>
                ) : null}
            </Menu>
        </>
    );
}

function CefpIssueMatrixGridCard({
    row,
    rowNumber,
    language,
    showRemark,
    plenaryEscalationControl,
    statusEditControl,
    onView,
    onEdit,
    onRemove,
}: {
    row: CefpIssueMatrixRow;
    rowNumber: number;
    language: CefpIssueMatrixLanguage;
    showRemark: boolean;
    plenaryEscalationControl?: CefpPlenaryEscalationControl;
    statusEditControl?: CefpStatusEditControl;
    onView?: (row: CefpIssueMatrixRow) => void;
    onEdit?: (row: CefpIssueMatrixRow) => void;
    onRemove?: (row: CefpIssueMatrixRow) => void;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";
    const text = GRID_TEXT[language];

    return (
        <Paper
            elevation={0}
            sx={{
                borderRadius: 2,
                border: "1px solid",
                borderColor: isDark
                    ? alpha("#FFFFFF", 0.12)
                    : "#E9EAEB",
                bgcolor: "background.paper",
                backgroundImage: "none",
                px: {
                    xs: 2,
                    md: 2.5,
                },
                py: {
                    xs: 2,
                    md: 2.25,
                },
            }}
        >
            <Box
                sx={{
                    display: "flex",
                    alignItems: "flex-start",
                    justifyContent: "space-between",
                    gap: 2,
                }}
            >
                <Box sx={{ minWidth: 0 }}>
                    <GridLabel language={language}>
                        {text.workingGroup}
                    </GridLabel>

                    <Typography
                        title={normalizeText(row.workingGroup)}
                        sx={{
                            mt: 0.4,
                            minWidth: 0,
                            overflow: "hidden",
                            color: "text.primary",
                            fontFamily: getFontFamily(language),
                            fontSize: 15,
                            fontWeight: 600,
                            lineHeight: 1.45,
                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                        }}
                    >
                        {normalizeText(row.workingGroup)}
                    </Typography>
                </Box>

                <GridActionMenu
                    row={row}
                    language={language}
                    onView={onView}
                    onEdit={onEdit}
                    onRemove={onRemove}
                />
            </Box>

            <Box
                sx={{
                    mt: 2.25,
                    display: "grid",
                    gridTemplateColumns: {
                        xs: "1fr",
                        md: "minmax(0, 1fr) minmax(0, 1fr)",
                    },
                    columnGap: {
                        xs: 2,
                        md: 4,
                        lg: 5,
                    },
                    rowGap: 2.25,
                    alignItems: "start",
                }}
            >
                <Box
                    sx={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 1.75,
                        minWidth: 0,
                    }}
                >
                    <GridMetaRow
                        label={`${text.number} :`}
                        labelWidth={LEFT_META_LABEL_WIDTH}
                        language={language}
                    >
                        <GridValueText language={language}>
                            {rowNumber}
                        </GridValueText>
                    </GridMetaRow>

                    <GridMetaRow
                        label={`${text.ministry} :`}
                        labelWidth={LEFT_META_LABEL_WIDTH}
                        language={language}
                    >
                        <GridValueSlot
                            leading={
                                row.primaryAgency &&
                                    row.primaryAgency !== "-" ? (
                                    <MinistryAvatar
                                        row={row}
                                        language={language}
                                    />
                                ) : undefined
                            }
                        >
                            <GridValueText language={language}>
                                {normalizeText(row.primaryAgency)}
                            </GridValueText>
                        </GridValueSlot>
                    </GridMetaRow>

                    <GridMetaRow
                        label={`${text.status} :`}
                        labelWidth={LEFT_META_LABEL_WIDTH}
                        language={language}
                    >
                        <GridStatusControl
                            row={row}
                            language={language}
                            control={statusEditControl}
                        />
                    </GridMetaRow>
                </Box>

                <Box
                    sx={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 1.75,
                        minWidth: 0,
                    }}
                >
                    <GridMetaRow
                        label={`${text.category} :`}
                        labelWidth={RIGHT_META_LABEL_WIDTH}
                        language={language}
                    >
                        <GridValueText language={language}>
                            {normalizeText(row.category)}
                        </GridValueText>
                    </GridMetaRow>

                    <GridMetaRow
                        label={`${text.issue} :`}
                        labelWidth={RIGHT_META_LABEL_WIDTH}
                        language={language}
                    >
                        <GridValueText language={language} wrap>
                            {normalizeText(row.issue)}
                        </GridValueText>
                    </GridMetaRow>

                    <GridMetaRow
                        label={`${text.escalation} :`}
                        labelWidth={RIGHT_META_LABEL_WIDTH}
                        language={language}
                    >
                        <GridEscalationControl
                            row={row}
                            language={language}
                            control={plenaryEscalationControl}
                        />
                    </GridMetaRow>
                </Box>
            </Box>

            <Box
                sx={{
                    mt: 2.5,
                    pt: 2.25,
                    borderTop: "1px solid",
                    borderColor: "divider",

                    display: "grid",
                    gridTemplateColumns: {
                        xs: "1fr",
                        md: "minmax(0, 1fr) minmax(0, 1fr)",
                    },
                    columnGap: {
                        xs: 2,
                        md: 4,
                        lg: 5,
                    },
                    rowGap: 2.5,
                    alignItems: "start",
                }}
            >
                <Box
                    sx={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 2.5,
                        minWidth: 0,
                    }}
                >
                    <GridContentBlock
                        label={text.description}
                        value={row.issueDescription}
                        language={language}
                    />

                    <GridContentBlock
                        label={text.recommendation}
                        value={row.recommendation}
                        language={language}
                    />
                </Box>

                <Box
                    sx={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 2.5,
                        minWidth: 0,
                    }}
                >
                    <GridContentBlock
                        label={text.rgcDecision}
                        value={row.governmentDecision}
                        language={language}
                    />

                    <GridContentBlock
                        label={text.nextStep}
                        value={row.nextStep}
                        language={language}
                    />

                    {showRemark ? (
                        <GridContentBlock
                            label={text.remark}
                            value={row.remark}
                            language={language}
                        />
                    ) : null}
                </Box>
            </Box>
        </Paper>
    );
}

export function CefpIssueMatrixGrid({
    rows,
    language,
    loading = false,
    error = null,
    showRemark = false,
    plenaryEscalationControl,
    statusEditControl,
    onView,
    onEdit,
    onRemove,
}: CefpIssueMatrixGridProps) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";
    const text = GRID_TEXT[language];

    const [page, setPage] = useState(1);

    const pageCount = Math.max(
        1,
        Math.ceil(rows.length / PAGE_SIZE),
    );

    const currentPage = Math.min(
        page,
        pageCount,
    );

    const paginatedRows = useMemo(() => {
        const start = (currentPage - 1) * PAGE_SIZE;

        return rows.slice(
            start,
            start + PAGE_SIZE,
        );
    }, [
        currentPage,
        rows,
    ]);

    if (error) {
        return (
            <Alert
                severity="error"
                sx={{
                    borderRadius: 2,
                    fontFamily: getFontFamily(language),
                }}
            >
                {error}
            </Alert>
        );
    }

    if (loading) {
        return (
            <Paper
                elevation={0}
                sx={{
                    minHeight: 240,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    borderRadius: 2,
                    border: "1px solid",
                    borderColor: "divider",
                    bgcolor: "background.paper",
                    backgroundImage: "none",
                }}
            >
                <CircularProgress size={28} />
            </Paper>
        );
    }

    if (rows.length === 0) {
        return (
            <Paper
                elevation={0}
                sx={{
                    borderRadius: 2,
                    border: "1px solid",
                    borderColor: isDark
                        ? alpha("#FFFFFF", 0.12)
                        : "#E9EAEB",
                    bgcolor: "background.paper",
                    backgroundImage: "none",
                    px: 3,
                    py: 6,
                    textAlign: "center",
                }}
            >
                <Typography
                    sx={{
                        color: "text.secondary",
                        fontFamily: getFontFamily(language),
                        fontSize: 14,
                    }}
                >
                    {text.noData}
                </Typography>
            </Paper>
        );
    }

    return (
        <Box>
            <Box
                sx={{
                    display: "flex",
                    flexDirection: "column",
                    gap: 2.5,
                }}
            >
                {paginatedRows.map(
                    (row, index) => {
                        const rowNumber =
                            rows.length -
                            ((currentPage - 1) * PAGE_SIZE + index);

                        return (
                            <CefpIssueMatrixGridCard
                                key={row.id}
                                row={row}
                                rowNumber={rowNumber}
                                language={language}
                                showRemark={showRemark}
                                plenaryEscalationControl={
                                    plenaryEscalationControl
                                }
                                statusEditControl={
                                    statusEditControl
                                }
                                onView={onView}
                                onEdit={onEdit}
                                onRemove={onRemove}
                            />
                        );
                    },
                )}
            </Box>

            {pageCount > 1 ? (
                <Paper
                    elevation={0}
                    sx={{
                        mt: 2,
                        minHeight: 64,
                        px: 2,
                        py: 1.25,

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

                        borderRadius: 2,
                        border: "1px solid",
                        borderColor: isDark
                            ? alpha("#FFFFFF", 0.12)
                            : "#E9EAEB",

                        bgcolor: "background.paper",
                        backgroundImage: "none",
                    }}
                >
                    <Pagination
                        page={currentPage}
                        count={pageCount}
                        shape="rounded"
                        color="primary"
                        onChange={(
                            _event,
                            nextPage,
                        ) => {
                            setPage(nextPage);
                        }}
                        sx={{
                            "& .MuiPaginationItem-root": {
                                fontFamily: getFontFamily(language),
                            },
                        }}
                    />
                </Paper>
            ) : null}
        </Box>
    );
}