"use client";

import {
    useMemo,
    useState,
    type ReactNode,
} 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,
    CircularProgress,
    IconButton,
    Link,
    Paper,
    Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Typography,
} from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";

import type { RgcDecisionRow } from "../rgc-decision-data";
import { RgcDecisionStatusChip } from "./rgc-decision-status-chip";

const ROWS_PER_PAGE = 10;
const ROW_HEIGHT = 64;

function MinistryLogo({
    ministry,
    logo,
}: {
    ministry: string;
    logo?: string | null;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";

    const shortName =
        ministry
            .trim()
            .split(/\s+/)
            .map((word) => word.charAt(0))
            .join("")
            .slice(0, 3)
            .toUpperCase() || "M";

    return (
        <Avatar
            src={logo || undefined}
            alt={ministry}
            sx={{
                width: 28,
                height: 28,
                bgcolor: theme.palette.background.paper,
                color: theme.palette.primary.main,
                border: `1px solid ${
                    isDark
                        ? alpha(theme.palette.primary.light, 0.7)
                        : theme.palette.primary.main
                }`,
                fontSize: 8,
                fontWeight: 800,
                flexShrink: 0,
            }}
        >
            {shortName}
        </Avatar>
    );
}

function EllipsisText({
    children,
}: {
    children: ReactNode;
}) {
    const theme = useTheme();

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

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 PaginationBar({
    currentPage,
    totalPages,
    onPageChange,
}: {
    currentPage: number;
    totalPages: number;
    onPageChange: (page: number) => void;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";

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

    const buttonSx = {
        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 (
        <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={currentPage <= 1}
                    startIcon={
                        <ArrowBackRoundedIcon
                            sx={{ fontSize: 16 }}
                        />
                    }
                    onClick={() =>
                        onPageChange(
                            currentPage - 1,
                        )
                    }
                    sx={buttonSx}
                >
                    Previous
                </Button>
            </Box>

            <Stack
                direction="row"
                spacing={0.7}
                sx={{
                    flex: 1,
                    minWidth: 0,
                    alignItems: "center",
                    justifyContent: "center",
                    flexWrap: "wrap",
                }}
            >
                {pages.map((page, index) => {
                    if (page === "...") {
                        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 =
                        page === currentPage;

                    return (
                        <Button
                            key={page}
                            variant="text"
                            onClick={() =>
                                onPageChange(page)
                            }
                            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,
                                          ),
                                },
                            }}
                        >
                            {page}
                        </Button>
                    );
                })}
            </Stack>

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

export function RgcDecisionTable({
    rows,
    loading,
    onViewDetail,
}: {
    rows: RgcDecisionRow[];
    loading?: boolean;
    onViewDetail: (row: RgcDecisionRow) => void;
}) {
    const theme = useTheme();
    const isDark =
        theme.palette.mode === "dark";

    const [
        paginationState,
        setPaginationState,
    ] = useState<{
        rowsLength: number;
        page: number;
    }>({
        rowsLength: rows.length,
        page: 1,
    });

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

    const requestedPage =
        paginationState.rowsLength ===
        rows.length
            ? paginationState.page
            : 1;

    const currentPage = Math.min(
        Math.max(requestedPage, 1),
        totalPages,
    );

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

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

    const emptyRowsCount = Math.max(
        0,
        ROWS_PER_PAGE -
            paginatedRows.length,
    );

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

        setPaginationState({
            rowsLength: rows.length,
            page: safePage,
        });
    };

    const headerCellSx = {
        height: 49,
        py: 0,
        px: 1.4,
        color: theme.palette.text.secondary,
        fontSize: 13,
        fontWeight: 500,
        borderColor: isDark
            ? alpha("#FFFFFF", 0.08)
            : "#FFFFFF",
        bgcolor: isDark
            ? alpha(
                  theme.palette.primary.main,
                  0.18,
              )
            : "#DCEEFF",
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
    };

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

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

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

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

                    "&::-webkit-scrollbar-thumb":
                        {
                            bgcolor: isDark
                                ? alpha(
                                      "#FFFFFF",
                                      0.24,
                                  )
                                : "#CBD5E1",
                            borderRadius: 99,
                        },
                }}
            >
                <Table
                    sx={{
                        minWidth: 2100,
                        tableLayout: "fixed",
                    }}
                >
                    <TableHead>
                        <TableRow>
                            <TableCell
                                sx={{
                                    ...headerCellSx,
                                    width: 70,
                                }}
                            >
                                No
                            </TableCell>

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

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

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

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

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

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

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

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

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

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

                    <TableBody>
                        {loading ? (
                            <TableRow>
                                <TableCell
                                    colSpan={11}
                                    sx={{
                                        height:
                                            ROW_HEIGHT *
                                            ROWS_PER_PAGE,
                                        py: 8,
                                        textAlign:
                                            "center",
                                    }}
                                >
                                    <CircularProgress
                                        size={28}
                                    />
                                </TableCell>
                            </TableRow>
                        ) : null}

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

                                    return (
                                        <TableRow
                                            key={
                                                row.id
                                            }
                                            hover
                                            sx={{
                                                height: ROW_HEIGHT,
                                                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
                                                }
                                            >
                                                <Stack
                                                    direction="row"
                                                    spacing={
                                                        1.2
                                                    }
                                                    sx={{
                                                        alignItems:
                                                            "center",
                                                        minWidth: 0,
                                                    }}
                                                >
                                                    <MinistryLogo
                                                        ministry={
                                                            row.ministry
                                                        }
                                                        logo={
                                                            row.ministryLogo
                                                        }
                                                    />

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

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

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

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

                                            <TableCell
                                                sx={
                                                    bodyCellSx
                                                }
                                            >
                                                <RgcDecisionStatusChip
                                                    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"
                                                        sx={{
                                                            display:
                                                                "block",
                                                            width:
                                                                "100%",
                                                            maxWidth:
                                                                "100%",
                                                            color:
                                                                theme
                                                                    .palette
                                                                    .primary
                                                                    .main,
                                                            fontSize: 13,
                                                            fontWeight: 700,
                                                            overflow:
                                                                "hidden",
                                                            textOverflow:
                                                                "ellipsis",
                                                            whiteSpace:
                                                                "nowrap",
                                                        }}
                                                    >
                                                        View Source
                                                    </Link>
                                                ) : (
                                                    "-"
                                                )}
                                            </TableCell>

                                            <TableCell
                                                sx={{
                                                    ...bodyCellSx,
                                                    overflow:
                                                        "visible",
                                                }}
                                            >
                                                <Stack
                                                    direction="row"
                                                    spacing={0.6}
                                                    role="button"
                                                    tabIndex={0}
                                                    onClick={() =>
                                                        onViewDetail(row)
                                                    }
                                                    onKeyDown={(event) => {
                                                        if (
                                                            event.key === "Enter" ||
                                                            event.key === " "
                                                        ) {
                                                            event.preventDefault();
                                                            onViewDetail(row);
                                                        }
                                                    }}
                                                    sx={{
                                                        alignItems: "center",
                                                        flexWrap: "nowrap",
                                                        whiteSpace: "nowrap",
                                                        minWidth: 130,
                                                        width: "fit-content",
                                                        cursor: "pointer",
                                                        userSelect: "none",
                                                        color:
                                                            theme.palette.text
                                                                .secondary,
                                                        "&:hover": {
                                                            color:
                                                                theme.palette
                                                                    .primary.main,
                                                        },
                                                    }}
                                                >
                                                    <IconButton
                                                        size="small"
                                                        aria-label={`View detail for ${row.ministry}`}
                                                        sx={{
                                                            p: 0.2,
                                                            color:
                                                                theme
                                                                    .palette
                                                                    .text
                                                                    .secondary,
                                                            flexShrink: 0,
                                                        }}
                                                    >
                                                        <RemoveRedEyeOutlinedIcon
                                                            sx={{
                                                                fontSize: 15,
                                                            }}
                                                        />
                                                    </IconButton>

                                                    <Button
                                                        variant="text"
                                                        sx={{
                                                            minWidth: 0,
                                                            p: 0,
                                                            color:
                                                                theme
                                                                    .palette
                                                                    .text
                                                                    .secondary,
                                                            fontSize: 12,
                                                            fontWeight: 500,
                                                            lineHeight:
                                                                "18px",
                                                            whiteSpace:
                                                                "nowrap",
                                                            textTransform:
                                                                "none",
                                                            flexShrink: 0,
                                                            "&:hover": {
                                                                bgcolor:
                                                                    "transparent",
                                                                color:
                                                                    theme
                                                                        .palette
                                                                        .primary
                                                                        .main,
                                                            },
                                                        }}
                                                    >
                                                        View Detail
                                                    </Button>
                                                </Stack>
                                            </TableCell>
                                        </TableRow>
                                    );
                                },
                            )}

                        {!loading &&
                            rows.length > 0 &&
                            Array.from({
                                length: emptyRowsCount,
                            }).map(
                                (_, index) => (
                                    <TableRow
                                        key={`empty-row-${index}`}
                                        sx={{
                                            height: ROW_HEIGHT,
                                            bgcolor:
                                                theme
                                                    .palette
                                                    .background
                                                    .paper,
                                        }}
                                    >
                                        <TableCell
                                            colSpan={
                                                11
                                            }
                                            sx={{
                                                height: ROW_HEIGHT,
                                                py: 0,
                                                borderColor:
                                                    theme
                                                        .palette
                                                        .divider,
                                            }}
                                        />
                                    </TableRow>
                                ),
                            )}

                        {!loading &&
                        rows.length === 0 ? (
                            <>
                                <TableRow>
                                    <TableCell
                                        colSpan={11}
                                        sx={{
                                            height: ROW_HEIGHT,
                                            textAlign:
                                                "center",
                                            color:
                                                theme
                                                    .palette
                                                    .text
                                                    .secondary,
                                            fontSize: 13,
                                            borderColor:
                                                theme
                                                    .palette
                                                    .divider,
                                        }}
                                    >
                                        No RGC
                                        Decision found.
                                    </TableCell>
                                </TableRow>

                                {Array.from({
                                    length:
                                        ROWS_PER_PAGE -
                                        1,
                                }).map(
                                    (_, index) => (
                                        <TableRow
                                            key={`empty-no-data-${index}`}
                                            sx={{
                                                height: ROW_HEIGHT,
                                                bgcolor:
                                                    theme
                                                        .palette
                                                        .background
                                                        .paper,
                                            }}
                                        >
                                            <TableCell
                                                colSpan={
                                                    11
                                                }
                                                sx={{
                                                    height: ROW_HEIGHT,
                                                    py: 0,
                                                    borderColor:
                                                        theme
                                                            .palette
                                                            .divider,
                                                }}
                                            />
                                        </TableRow>
                                    ),
                                )}
                            </>
                        ) : null}
                    </TableBody>
                </Table>
            </TableContainer>

            {!loading ? (
                <PaginationBar
                    currentPage={currentPage}
                    totalPages={totalPages}
                    onPageChange={
                        handlePageChange
                    }
                />
            ) : null}
        </Paper>
    );
}

export default RgcDecisionTable;