"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(
    value?: string | null,
): string {
    if (!value) {
        return "";
    }

    return value
        .replace(
            /<[^>]*>/g,
            " ",
        )
        .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 formatDate(
    value?: string | null,
): string {
    if (!value) {
        return "-";
    }

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

    if (!match) {
        return value;
    }

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

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

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

    return (
        <Box
            sx={{
                display: "grid",

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

                gap: 1,

                alignItems:
                    "center",

                minWidth: 0,
            }}
        >
            <Typography
                sx={{
                    color:
                        theme.palette
                            .text.secondary,

                    fontSize: 12,
                }}
            >
                {label}
            </Typography>

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

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

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

    const styles =
        status === "Solved"
            ? {
                color: isDark
                    ? "#86EFAC"
                    : "#16A34A",

                border:
                    "#86EFAC",

                bg: isDark
                    ? alpha(
                        "#22C55E",
                        0.14,
                    )
                    : "#F0FDF4",
            }
            : status ===
                "In Progress"
                ? {
                    color: isDark
                        ? "#FCD34D"
                        : "#D97706",

                    border:
                        "#FCD34D",

                    bg: isDark
                        ? alpha(
                            "#F59E0B",
                            0.14,
                        )
                        : "#FFFBEB",
                }
                : {
                    color: isDark
                        ? "#FCA5A5"
                        : "#DC2626",

                    border:
                        "#FCA5A5",

                    bg: isDark
                        ? alpha(
                            "#EF4444",
                            0.14,
                        )
                        : "#FEF2F2",
                };

    return (
        <Chip
            label={status}
            size="small"
            variant="outlined"
            sx={{
                height: 26,

                minWidth: 105,

                width:
                    "fit-content",

                borderRadius:
                    99,

                color:
                    styles.color,

                borderColor:
                    styles.border,

                bgcolor:
                    styles.bg,

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

                    fontSize: 11,

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

function TextSection({
    label,
    value,
}: {
    label: string;

    value?: string | null;
}) {
    const theme =
        useTheme();

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

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

                    color:
                        theme.palette
                            .text.secondary,

                    fontSize: 12,
                }}
            >
                {label}
            </Typography>

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

                    fontSize: 13,

                    lineHeight: 1.5,

                    display:
                        "-webkit-box",

                    WebkitLineClamp:
                        3,

                    WebkitBoxOrient:
                        "vertical",

                    overflow:
                        "hidden",
                }}
            >
                {text}
            </Typography>
        </Box>
    );
}

function RgcDecisionGridCard({
    row,
    number,
    language,
}: {
    row: RgcDecisionRow;

    number: number;

    language: RgcDecisionLanguage;
}) {
    const theme =
        useTheme();

    const router =
        useRouter();

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

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

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

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

    const issues =
        Array.isArray(
            row.issues,
        )
            ? row.issues
                .map(
                    (issue) =>
                        String(
                            issue.title ??
                            "",
                        ).trim(),
                )
                .filter(Boolean)
                .join(", ")
            : "";

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

    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,
            }}
        >
            {/* HEADER */}
            <Box
                sx={{
                    mb: 2,

                    pb: 2,

                    display: "flex",

                    justifyContent:
                        "space-between",

                    alignItems:
                        "center",

                    gap: 2,

                    borderBottom:
                        "1px solid",

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

                        flex: 1,

                        fontSize: 15,

                        fontWeight: 700,

                        overflow:
                            "hidden",

                        textOverflow:
                            "ellipsis",

                        whiteSpace:
                            "nowrap",
                    }}
                >
                    {issues ||
                        stripHtml(
                            row.decision,
                        ) ||
                        "RGC Decision"}
                </Typography>

                <Button
                    type="button"
                    startIcon={
                        <VisibilityOutlinedIcon
                            sx={{
                                fontSize: 18,
                            }}
                        />
                    }
                    onClick={() =>
                        router.push(
                            `/cdc/rgc-decision/${row.id}`,
                        )
                    }
                    sx={{
                        flexShrink: 0,

                        textTransform:
                            "none",

                        color:
                            theme.palette
                                .text.secondary,

                        fontSize: 12,
                    }}
                >
                    {language === "kh"
                        ? "មើលលម្អិត"
                        : "View Detail"}
                </Button>
            </Box>

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

                    display: "grid",

                    gridTemplateColumns:
                    {
                        xs: "1fr",

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

                    columnGap: 6,

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

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

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

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

                                alignItems:
                                    "center",

                                gap: 1,
                            }}
                        >
                            <Avatar
                                src={
                                    logoUrl &&
                                        !logoFailed
                                        ? logoUrl
                                        : undefined
                                }
                                slotProps={{
                                    img: {
                                        onError:
                                            () =>
                                                setLogoFailed(
                                                    true,
                                                ),
                                    },
                                }}
                                sx={{
                                    width: 28,

                                    height: 28,

                                    fontSize: 11,

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

                                    color:
                                        theme.palette
                                            .primary.main,
                                }}
                            >
                                {!logoUrl ||
                                    logoFailed
                                    ? ministry
                                        .charAt(0)
                                        .toUpperCase()
                                    : null}
                            </Avatar>

                            <Typography
                                sx={{
                                    fontSize: 12,

                                    fontWeight: 600,
                                }}
                            >
                                {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={{
                                fontSize: 12,

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

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

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

                    <LabelValue
                        label={
                            language === "kh"
                                ? "មន្ត្រីសម្របសម្រួល :"
                                : "Focal Person :"
                        }
                    >
                        <Typography
                            sx={{
                                fontSize: 12,

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

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

                    gridTemplateColumns:
                    {
                        xs: "1fr",

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

                    columnGap: 6,

                    rowGap: 2.25,
                }}
            >
                <TextSection
                    label={
                        language === "kh"
                            ? "បញ្ហាពាក់ព័ន្ធ"
                            : "Linked Issues"
                    }
                    value={
                        issues
                    }
                />

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

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

                <Box
                    sx={{
                        minWidth: 0,
                    }}
                >
                    <Typography
                        sx={{
                            mb: 0.6,

                            color:
                                theme.palette
                                    .text.secondary,

                            fontSize: 12,
                        }}
                    >
                        {language === "kh"
                            ? "តំណភ្ជាប់"
                            : "Link to Verification"}
                    </Typography>

                    {verificationLink ? (
                        <Link
                            href={
                                verificationLink
                            }
                            target="_blank"
                            rel="noopener noreferrer"
                            underline="always"
                            title={
                                verificationLink
                            }
                            sx={{
                                display: "block",

                                maxWidth:
                                    "100%",

                                overflow:
                                    "hidden",

                                textOverflow:
                                    "ellipsis",

                                whiteSpace:
                                    "nowrap",

                                fontSize: 13,

                                fontWeight: 500,
                            }}
                        >
                            {verificationLink}
                        </Link>
                    ) : (
                        <Typography
                            sx={{
                                fontSize: 13,
                            }}
                        >
                            -
                        </Typography>
                    )}
                </Box>

                <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();

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

                    display: "flex",

                    alignItems:
                        "center",

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

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

                    display: "flex",

                    alignItems:
                        "center",

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

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

    return (
        <Box
            sx={{
                display: "grid",

                gridTemplateColumns:
                    "1fr",

                gap: 2,
            }}
        >
            {rows.map(
                (
                    row,
                    index,
                ) => (
                    <RgcDecisionGridCard
                        key={row.id}
                        row={row}
                        number={
                            index + 1
                        }
                        language={
                            language
                        }
                    />
                ),
            )}
        </Box>
    );
}

export default RgcDecisionGrid;