"use client";

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

import { useRouter } from "next/navigation";

import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";

import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Chip from "@mui/material/Chip";
import CircularProgress from "@mui/material/CircularProgress";
import Link from "@mui/material/Link";
import Typography from "@mui/material/Typography";

import {
    alpha,
    useTheme,
} from "@mui/material/styles";

import type {
    RgcDecisionRow,
} from "../data/rgc-decision-data";

import type {
    RgcDecisionLanguage,
} from "../data/rgc-decision-i18n";

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

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

function stripHtml(
    html?: string | null,
): string {
    if (!html) {
        return "";
    }

    return String(html)
        .replace(/<[^>]*>/g, " ")
        .replace(/&nbsp;/gi, " ")
        .replace(/&amp;/gi, "&")
        .replace(/&lt;/gi, "<")
        .replace(/&gt;/gi, ">")
        .replace(/&quot;/gi, '"')
        .replace(/&#39;/gi, "'")
        .replace(/\s+/g, " ")
        .trim();
}

function normalizeLogoUrl(
    value?: string | null,
): string {
    const logo =
        String(value ?? "").trim();

    if (!logo) {
        return "";
    }

    if (
        /^(https?:|data:|blob:)/i.test(
            logo,
        )
    ) {
        return logo;
    }

    return `${FILE_BASE_URL}${logo.startsWith("/")
            ? logo
            : `/${logo}`
        }`;
}

function getInitial(
    value?: string | null,
): string {
    return (
        Array.from(
            String(value ?? "").trim(),
        )[0]?.toUpperCase() ??
        "?"
    );
}

function formatDate(
    value?: string | null,
): string {
    const text =
        String(value ?? "").trim();

    if (!text) {
        return "-";
    }

    const match =
        /^(\d{4})-(\d{2})-(\d{2})/.exec(
            text,
        );

    if (!match) {
        return text;
    }

    const date =
        new Date(
            Number(match[1]),
            Number(match[2]) - 1,
            Number(match[3]),
        );

    if (
        Number.isNaN(
            date.getTime(),
        )
    ) {
        return text;
    }

    return new Intl.DateTimeFormat(
        "en-GB",
        {
            day: "2-digit",
            month: "short",
            year: "numeric",
        },
    ).format(date);
}

function StatusChip({
    status,
}: {
    status: RgcDecisionRow["status"];
}) {
    const theme =
        useTheme();

    const isDark =
        theme.palette.mode ===
        "dark";

    const styles =
        status === "Solved"
            ? {
                color: isDark
                    ? "#4ADE80"
                    : "#16A34A",

                borderColor:
                    "#86EFAC",

                bgcolor:
                    isDark
                        ? alpha(
                            "#22C55E",
                            0.12,
                        )
                        : "#F0FDF4",
            }
            : status ===
                "In Progress"
                ? {
                    color: isDark
                        ? "#FBBF24"
                        : "#D97706",

                    borderColor:
                        "#FCD34D",

                    bgcolor:
                        isDark
                            ? alpha(
                                "#F59E0B",
                                0.12,
                            )
                            : "#FFFBEB",
                }
                : {
                    color: isDark
                        ? "#FF8080"
                        : "#EF4444",

                    borderColor:
                        "#FCA5A5",

                    bgcolor:
                        isDark
                            ? alpha(
                                "#EF4444",
                                0.13,
                            )
                            : "#FEF2F2",
                };

    return (
        <Chip
            label={status}
            size="small"
            variant="outlined"
            sx={{
                width:
                    "fit-content",

                minWidth:
                    status ===
                        "Not Addressed"
                        ? 118
                        : 104,

                height: 26,

                borderRadius:
                    "999px",

                color:
                    styles.color,

                borderColor:
                    styles.borderColor,

                bgcolor:
                    styles.bgcolor,

                "& .MuiChip-label":
                {
                    px: 1.4,

                    fontSize: 11,

                    fontWeight: 700,
                },
            }}
        />
    );
}

function LabelValue({
    label,
    children,
}: {
    label: string;
    children: ReactNode;
}) {
    const theme =
        useTheme();

    return (
        <Box
            sx={{
                minWidth: 0,

                display: "grid",

                gridTemplateColumns:
                    "140px minmax(0, 1fr)",

                gap: 1,

                alignItems:
                    "center",
            }}
        >
            <Typography
                sx={{
                    color:
                        theme.palette.text
                            .secondary,

                    fontSize: 12,

                    fontWeight: 400,
                }}
            >
                {label}
            </Typography>

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

function TextSection({
    label,
    value,
}: {
    label: string;
    value?: string | null;
}) {
    const theme =
        useTheme();

    const displayValue =
        stripHtml(value) ||
        "-";

    return (
        <Box
            sx={{
                minWidth: 0,
            }}
        >
            <Typography
                sx={{
                    mb: 0.75,

                    color:
                        theme.palette.text
                            .secondary,

                    fontSize: 12,

                    fontWeight: 400,
                }}
            >
                {label}
            </Typography>

            <Typography
                sx={{
                    color:
                        theme.palette.text
                            .primary,

                    fontSize: 13,

                    fontWeight: 400,

                    lineHeight: 1.5,

                    display:
                        "-webkit-box",

                    WebkitBoxOrient:
                        "vertical",

                    WebkitLineClamp: 3,

                    overflow: "hidden",

                    overflowWrap:
                        "anywhere",
                }}
            >
                {displayValue}
            </Typography>
        </Box>
    );
}

function VerificationLinkSection({
    row,
    language,
}: {
    row: RgcDecisionRow;
    language: RgcDecisionLanguage;
}) {
    const theme =
        useTheme();

    const link =
        row.verificationLink?.trim() ||
        row.verificationDownloadUrl?.trim() ||
        "";

    return (
        <Box
            sx={{
                minWidth: 0,
            }}
        >
            <Typography
                sx={{
                    mb: 0.75,

                    color:
                        theme.palette.text
                            .secondary,

                    fontSize: 12,

                    fontWeight: 400,
                }}
            >
                {language === "kh"
                    ? "តំណភ្ជាប់ប្រភពផ្ទៀងផ្ទាត់"
                    : "Link to Verification Source"}
            </Typography>

            {link ? (
                <Link
                    href={link}
                    target="_blank"
                    rel="noopener noreferrer"
                    underline="always"
                    title={link}
                    onClick={(event) => {
                        event.stopPropagation();
                    }}
                    sx={{
                        display: "block",

                        width: "100%",

                        maxWidth: "100%",

                        color:
                            theme.palette.primary
                                .main,

                        fontSize: 13,

                        fontWeight: 500,

                        lineHeight: 1.5,

                        overflow: "hidden",

                        textOverflow:
                            "ellipsis",

                        whiteSpace: "nowrap",

                        cursor: "pointer",
                    }}
                >
                    {link}
                </Link>
            ) : (
                <Typography
                    sx={{
                        color:
                            theme.palette.text
                                .primary,

                        fontSize: 13,
                    }}
                >
                    -
                </Typography>
            )}
        </Box>
    );
}

type CardProps = {
    row: RgcDecisionRow;

    index: number;

    language: RgcDecisionLanguage;

    onViewDetail: () => void;
};

function RgcDecisionCard({
    row,
    index,
    language,
    onViewDetail,
}: CardProps) {
    const theme =
        useTheme();

    const isDark =
        theme.palette.mode ===
        "dark";

    const logoUrl =
        useMemo(
            () =>
                normalizeLogoUrl(
                    row.ministryLogo,
                ),
            [
                row.ministryLogo,
            ],
        );

    const [
        logoFailed,
        setLogoFailed,
    ] = useState(false);

    const showLogo =
        Boolean(logoUrl) &&
        !logoFailed;

    const ministry =
        row.primaryAgency ||
        row.ministry ||
        "-";

    const category =
        row.category ||
        row.measureCategory ||
        "-";

    const title =
        row.plenary?.trim() ||
        stripHtml(
            row.decision,
        ) ||
        "RGC Decision";

    return (
        <Box
            sx={{
                width: "100%",

                p: {
                    xs: 2,
                    md: 2.5,
                },

                border:
                    "1px solid",

                borderColor:
                    theme.palette.divider,

                borderRadius:
                    "12px",

                bgcolor:
                    theme.palette.background
                        .paper,

                transition:
                    "all 180ms ease",

                "&:hover": {
                    borderColor:
                        alpha(
                            theme.palette.primary
                                .main,
                            0.3,
                        ),

                    boxShadow:
                        isDark
                            ? "0 8px 28px rgba(0,0,0,0.22)"
                            : "0 8px 28px rgba(16,24,40,0.06)",
                },
            }}
        >
            {/* HEADER */}
            <Box
                sx={{
                    display: "flex",

                    alignItems: "center",

                    justifyContent:
                        "space-between",

                    gap: 2,

                    pb: 2,

                    borderBottom:
                        "1px solid",

                    borderColor:
                        theme.palette.divider,
                }}
            >
                <Typography
                    title={title}
                    sx={{
                        minWidth: 0,

                        flex: 1,

                        color:
                            theme.palette.text
                                .primary,

                        fontSize: 15,

                        fontWeight: 700,

                        overflow: "hidden",

                        textOverflow:
                            "ellipsis",

                        whiteSpace: "nowrap",
                    }}
                >
                    {title}
                </Typography>

                <Button
                    type="button"
                    startIcon={
                        <VisibilityOutlinedIcon
                            sx={{
                                fontSize: 18,
                            }}
                        />
                    }
                    onClick={
                        onViewDetail
                    }
                    sx={{
                        flexShrink: 0,

                        minWidth: "auto",

                        px: 1,

                        color:
                            theme.palette.text
                                .secondary,

                        fontSize: 12,

                        fontWeight: 500,

                        textTransform:
                            "none",

                        "&:hover": {
                            color:
                                theme.palette.primary
                                    .main,

                            bgcolor:
                                alpha(
                                    theme.palette.primary
                                        .main,
                                    0.06,
                                ),
                        },
                    }}
                >
                    {language === "kh"
                        ? "មើលលម្អិត"
                        : "View Detail"}
                </Button>
            </Box>

            {/* SUMMARY */}
            <Box
                sx={{
                    pt: 2,

                    pb: 1,

                    display: "grid",

                    gridTemplateColumns:
                    {
                        xs: "1fr",

                        md: "repeat(2, minmax(0, 1fr))",
                    },

                    columnGap: 5,

                    rowGap: 2,
                }}
            >
                {/* LEFT */}
                <Box
                    sx={{
                        display: "grid",

                        gap: 2,
                    }}
                >
                    <LabelValue
                        label="No. :"
                    >
                        <Typography
                            sx={{
                                fontSize: 12,

                                fontWeight: 500,
                            }}
                        >
                            {index + 1}
                        </Typography>
                    </LabelValue>

                    <LabelValue
                        label={
                            language === "kh"
                                ? "ក្រសួង :"
                                : "Ministry :"
                        }
                    >
                        <Box
                            sx={{
                                minWidth: 0,

                                display: "flex",

                                alignItems: "center",

                                gap: 1,
                            }}
                        >
                            <Avatar
                                src={
                                    showLogo
                                        ? logoUrl
                                        : undefined
                                }
                                slotProps={{
                                    img: {
                                        onError:
                                            () =>
                                                setLogoFailed(
                                                    true,
                                                ),
                                    },
                                }}
                                sx={{
                                    width: 26,

                                    height: 26,

                                    flexShrink: 0,

                                    border:
                                        "1px solid",

                                    borderColor:
                                        theme.palette
                                            .primary.main,

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

                                    color:
                                        theme.palette
                                            .primary.main,

                                    fontSize: 10,

                                    fontWeight: 700,

                                    "& img": {
                                        objectFit:
                                            "contain",

                                        p: "1px",
                                    },
                                }}
                            >
                                {!showLogo
                                    ? getInitial(
                                        ministry,
                                    )
                                    : null}
                            </Avatar>

                            <Typography
                                sx={{
                                    minWidth: 0,

                                    color:
                                        theme.palette.text
                                            .primary,

                                    fontSize: 12,

                                    fontWeight: 600,

                                    overflow: "hidden",

                                    textOverflow:
                                        "ellipsis",

                                    whiteSpace: "nowrap",
                                }}
                            >
                                {ministry}
                            </Typography>
                        </Box>
                    </LabelValue>

                    <LabelValue
                        label={
                            language === "kh"
                                ? "ស្ថានភាព :"
                                : "Status :"
                        }
                    >
                        <StatusChip
                            status={
                                row.status
                            }
                        />
                    </LabelValue>
                </Box>

                {/* RIGHT */}
                <Box
                    sx={{
                        display: "grid",

                        gap: 2,

                        alignContent:
                            "start",
                    }}
                >
                    <LabelValue
                        label={
                            language === "kh"
                                ? "ប្រភេទ :"
                                : "Category :"
                        }
                    >
                        <Typography
                            sx={{
                                textAlign: "left",

                                fontSize: 12,

                                fontWeight: 600,
                            }}
                        >
                            {category}
                        </Typography>
                    </LabelValue>

                    <LabelValue
                        label={
                            language === "kh"
                                ? "កាលបរិច្ឆេទប្រជុំ :"
                                : "Meeting Date :"
                        }
                    >
                        <Typography
                            sx={{
                                textAlign: "left",

                                fontSize: 12,

                                fontWeight: 600,
                            }}
                        >
                            {formatDate(
                                row.meetingDate ||
                                row.effectiveDate,
                            )}
                        </Typography>
                    </LabelValue>

                    <LabelValue
                        label={
                            language === "kh"
                                ? "មន្ត្រីទទួលបន្ទុក :"
                                : "Focal Person :"
                        }
                    >
                        <Typography
                            sx={{
                                textAlign: "left",

                                fontSize: 12,

                                fontWeight: 600,
                            }}
                        >
                            {row.focalPerson ||
                                "-"}
                        </Typography>
                    </LabelValue>
                </Box>
            </Box>

            {/* DATA - NO TOP BORDER */}
            <Box
                sx={{
                    pt: 1,

                    display: "grid",

                    gridTemplateColumns:
                    {
                        xs: "1fr",

                        md: "repeat(2, minmax(0, 1fr))",
                    },

                    columnGap: 5,

                    rowGap: 2.25,
                }}
            >
                <TextSection
                    label={
                        language === "kh"
                            ? "សូចនាករ"
                            : "Indicator"
                    }
                    value={
                        row.indicator
                    }
                />

                <TextSection
                    label={
                        language === "kh"
                            ? "មន្ត្រីទទួលបន្ទុក"
                            : "Focal Person"
                    }
                    value={
                        row.focalPerson
                    }
                />

                <TextSection
                    label={
                        language === "kh"
                            ? "ប្រភពផ្ទៀងផ្ទាត់"
                            : "Source of Verification"
                    }
                    value={
                        row.sourceOfVerification
                    }
                />

                <VerificationLinkSection
                    row={row}
                    language={language}
                />

                <Box
                    sx={{
                        gridColumn: {
                            xs: "auto",

                            md: "1 / -1",
                        },
                    }}
                >
                    <TextSection
                        label={
                            language === "kh"
                                ? "សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល"
                                : "RGC Decision"
                        }
                        value={
                            row.decision
                        }
                    />
                </Box>
            </Box>
        </Box>
    );
}

export function RgcDecisionGrid({
    rows,
    language,
    loading = false,
}: Props) {
    const theme =
        useTheme();

    const router =
        useRouter();

    if (loading) {
        return (
            <Box
                sx={{
                    minHeight: 320,

                    display: "flex",

                    alignItems: "center",

                    justifyContent:
                        "center",
                }}
            >
                <CircularProgress
                    size={30}
                />
            </Box>
        );
    }

    if (
        rows.length === 0
    ) {
        return (
            <Box
                sx={{
                    minHeight: 320,

                    display: "flex",

                    alignItems: "center",

                    justifyContent:
                        "center",

                    border:
                        "1px solid",

                    borderColor:
                        theme.palette.divider,

                    borderRadius:
                        "12px",

                    bgcolor:
                        theme.palette.background
                            .paper,
                }}
            >
                <Typography
                    sx={{
                        color:
                            theme.palette.text
                                .secondary,

                        fontSize: 13,
                    }}
                >
                    {language === "kh"
                        ? "មិនមានទិន្នន័យ"
                        : "No data found"}
                </Typography>
            </Box>
        );
    }

    return (
        <Box
            sx={{
                width: "100%",

                display: "grid",

                gridTemplateColumns:
                    "1fr",

                gap: 2,
            }}
        >
            {rows.map(
                (
                    row,
                    index,
                ) => (
                    <RgcDecisionCard
                        key={
                            row.id
                        }
                        row={
                            row
                        }
                        index={
                            index
                        }
                        language={
                            language
                        }
                        onViewDetail={() =>
                            router.push(
                                `/cefp/rgc-decision/${row.id}`,
                            )
                        }
                    />
                ),
            )}
        </Box>
    );
}

export default RgcDecisionGrid;