"use client";

import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import LocalOfferOutlinedIcon from "@mui/icons-material/LocalOfferOutlined";
import PersonOutlineRoundedIcon from "@mui/icons-material/PersonOutlineRounded";
import ViewWeekOutlinedIcon from "@mui/icons-material/ViewWeekOutlined";

import {
    Avatar,
    Box,
    Button,
    Divider,
    Link,
    Paper,
    Stack,
    Typography,
} from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";

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

type RgcDecisionDetailScreenProps = {
    row: RgcDecisionRow;
    onBack: () => void;
};

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

type RgcDecisionRowWithPlenary = RgcDecisionRow & {
    plenary?: PlenaryValue;
    plenaryName?: string | null;
    plenaryTitle?: string | null;
};

function cleanText(value: unknown): string {
    return typeof value === "string"
        ? value.trim()
        : "";
}

function getPlenaryTitle(
    row: RgcDecisionRow,
    isKhmer: boolean,
): string {
    const extendedRow =
        row as RgcDecisionRowWithPlenary;

    const nestedPlenaryName =
        extendedRow.plenary &&
        typeof extendedRow.plenary === "object"
            ? cleanText(extendedRow.plenary.name) ||
              cleanText(extendedRow.plenary.title)
            : cleanText(extendedRow.plenary);

    const plenaryName =
        cleanText(extendedRow.plenaryName) ||
        cleanText(extendedRow.plenaryTitle) ||
        nestedPlenaryName;

    if (plenaryName) {
        return plenaryName;
    }

    if (row.plenaryId) {
        return isKhmer
            ? `កិច្ចប្រជុំពេញអង្គ លេខ ${row.plenaryId}`
            : `Plenary #${row.plenaryId}`;
    }

    return isKhmer
        ? "សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល"
        : "RGC Decision";
}

function sanitizeRichTextHtml(
    value: string | null | undefined,
): string {
    const html = String(value ?? "").trim();

    if (!html) {
        return "";
    }

    return html
        .replace(
            /<\s*(script|style|iframe|object|embed)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi,
            "",
        )
        .replace(
            /\son\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,
            "",
        )
        .replace(
            /\s(href|src)\s*=\s*("|')\s*javascript:[\s\S]*?\2/gi,
            ' $1="#"',
        );
}

function MetaItem({
    icon,
    label,
    children,
}: {
    icon: React.ReactNode;
    label: string;
    children: React.ReactNode;
}) {
    const theme = useTheme();

    return (
        <Stack
            direction="row"
            spacing={0.9}
            sx={{
                minWidth: 0,
                alignItems: "center",
            }}
        >
            <Box
                sx={{
                    display: "grid",
                    placeItems: "center",
                    color: theme.palette.text.secondary,
                    flexShrink: 0,
                    "& svg": {
                        fontSize: 18,
                        strokeWidth: 1.5,
                    },
                }}
            >
                {icon}
            </Box>

            <Typography
                sx={{
                    color: theme.palette.text.secondary,
                    fontSize: 13,
                    fontWeight: 400,
                    lineHeight: "22px",
                    whiteSpace: "nowrap",
                    flexShrink: 0,
                }}
            >
                {label}
            </Typography>

            <Box
                sx={{
                    minWidth: 0,
                    color: theme.palette.text.primary,
                    fontSize: 13,
                    fontWeight: 500,
                    lineHeight: "22px",
                }}
            >
                {children}
            </Box>
        </Stack>
    );
}

function DetailField({
    label,
    value,
    isLink = false,
    isRichText = false,
}: {
    label: string;
    value?: string | null;
    isLink?: boolean;
    isRichText?: boolean;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";
    const text = value?.trim() || "-";

    return (
        <Box>
            <Typography
                sx={{
                    mb: 0.8,
                    color: theme.palette.text.primary,
                    fontSize: 13,
                    fontWeight: 700,
                    lineHeight: "22px",
                }}
            >
                {label}
            </Typography>

            <Paper
                elevation={0}
                sx={{
                    minHeight: 48,
                    px: 1.5,
                    py: 1.25,
                    display: "flex",
                    alignItems: "center",
                    borderRadius: "6px",
                    border: `1px solid ${theme.palette.divider}`,
                    bgcolor: isDark
                        ? alpha(theme.palette.common.white, 0.025)
                        : "#F7F7F8",
                }}
            >
                {isLink && value?.trim() ? (
                    <Link
                        href={value}
                        target="_blank"
                        rel="noopener noreferrer"
                        underline="always"
                        sx={{
                            color: theme.palette.primary.main,
                            fontSize: 13,
                            fontWeight: 400,
                            lineHeight: "20px",
                            overflowWrap: "anywhere",
                        }}
                    >
                        {value}
                    </Link>
                ) : isRichText && value?.trim() ? (
                    <Box
                        dangerouslySetInnerHTML={{
                            __html:
                                sanitizeRichTextHtml(
                                    value,
                                ),
                        }}
                        sx={{
                            width: "100%",
                            color:
                                theme.palette.text.primary,
                            fontSize: 13,
                            fontWeight: 400,
                            lineHeight: 1.65,
                            overflowWrap: "anywhere",

                            "& p": {
                                my: 0.5,
                            },

                            "& h1": {
                                my: 0.75,
                                fontSize: 22,
                                lineHeight: 1.35,
                            },

                            "& h2": {
                                my: 0.75,
                                fontSize: 18,
                                lineHeight: 1.4,
                            },

                            "& h3": {
                                my: 0.75,
                                fontSize: 16,
                                lineHeight: 1.45,
                            },

                            "& ul, & ol": {
                                my: 0.75,
                                pl: 3,
                            },

                            "& blockquote": {
                                my: 0.75,
                                mx: 0,
                                pl: 1.5,
                                borderLeft: `3px solid ${theme.palette.divider}`,
                                color:
                                    theme.palette.text.secondary,
                            },

                            "& pre": {
                                my: 0.75,
                                p: 1,
                                borderRadius: "4px",
                                bgcolor:
                                    theme.palette.action.hover,
                                whiteSpace: "pre-wrap",
                            },

                            "& a": {
                                color:
                                    theme.palette.primary.main,
                                textDecoration:
                                    "underline",
                            },
                        }}
                    />
                ) : (
                    <Typography
                        sx={{
                            color:
                                text === "-"
                                    ? theme.palette.text.secondary
                                    : theme.palette.text.primary,
                            fontSize: 13,
                            fontWeight: 400,
                            lineHeight: "20px",
                            whiteSpace: "pre-wrap",
                            overflowWrap: "anywhere",
                        }}
                    >
                        {text}
                    </Typography>
                )}
            </Paper>
        </Box>
    );
}

export function RgcDecisionDetailScreen({
    row,
    onBack,
}: RgcDecisionDetailScreenProps) {
    const theme = useTheme();
    const { language } = useAppLanguage();
    const isKhmer = language === "kh";

    const ministryInitial =
        row.ministry?.trim().charAt(0).toUpperCase() || "M";

    return (
        <Box
            sx={{
                width: "100%",
                minHeight: "calc(100vh - 64px)",
                px: {
                    xs: 2,
                    md: 3,
                },
                py: 2.5,
                bgcolor: theme.palette.background.default,
                color: theme.palette.text.primary,
            }}
        >
            <Stack
                direction="row"
                spacing={4}
                sx={{
                    mb: 3,
                    alignItems: "flex-start",
                    flexWrap: "wrap",
                }}
            >
                <Button
                    onClick={onBack}
                    startIcon={
                        <ArrowBackRoundedIcon
                            sx={{ fontSize: 16 }}
                        />
                    }
                    sx={{
                        mt: 0.15,
                        px: 0,
                        minWidth: 0,
                        color: theme.palette.text.secondary,
                        textTransform: "none",
                        fontSize: 13,
                        fontWeight: 400,
                        lineHeight: "22px",
                        flexShrink: 0,

                        "& .MuiButton-startIcon": {
                            mr: 0.7,
                        },

                        "&:hover": {
                            bgcolor: "transparent",
                            color: theme.palette.primary.main,
                        },
                    }}
                >
                    {isKhmer ? "ត្រឡប់ក្រោយ" : "Back"}
                </Button>

                <Box sx={{ minWidth: 0 }}>
                    <Typography
                        sx={{
                            color: theme.palette.text.primary,
                            fontSize: 20,
                            fontWeight: 700,
                            lineHeight: "28px",
                        }}
                    >
                        {isKhmer
                            ? "ព័ត៌មានលម្អិតសេចក្តីសម្រេច"
                            : "RGC Decision Detail"}
                    </Typography>

                    <Typography
                        sx={{
                            mt: 0.35,
                            color: theme.palette.text.secondary,
                            fontSize: 13,
                            fontWeight: 400,
                            lineHeight: "22px",
                        }}
                    >
                        {isKhmer
                            ? "ព័ត៌មានលម្អិតនៃសេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល"
                            : "Detail Information of RGC Decision"}
                    </Typography>
                </Box>
            </Stack>

            <Typography
                sx={{
                    mb: 1.5,
                    color: theme.palette.text.primary,
                    fontSize: {
                        xs: 22,
                        md: 26,
                    },
                    fontWeight: 700,
                    lineHeight: 1.35,
                    overflowWrap: "anywhere",
                }}
            >
                {getPlenaryTitle(
                    row,
                    isKhmer,
                )}
            </Typography>

            <Box
                sx={{
                    mb: 2.5,
                    px: {
                        xs: 0,
                        md: 0.5,
                    },
                }}
            >
                <Box
                    sx={{
                        pb: 2,
                    }}
                >
                    <MetaItem
                        icon={<PersonOutlineRoundedIcon />}
                        label={isKhmer ? "ក្រសួង/ស្ថាប័ន" : "Ministry"}
                    >
                        <Stack
                            direction="row"
                            spacing={0.8}
                            sx={{
                                minWidth: 0,
                                alignItems: "center",
                            }}
                        >
                            <Avatar
                                src={row.ministryLogo || undefined}
                                alt={row.ministry}
                                sx={{
                                    width: 22,
                                    height: 22,
                                    bgcolor: theme.palette.background.paper,
                                    color: theme.palette.primary.main,
                                    border: `1px solid ${theme.palette.primary.main}`,
                                    fontSize: 9,
                                    fontWeight: 800,
                                    flexShrink: 0,
                                }}
                            >
                                {ministryInitial}
                            </Avatar>

                            <Typography
                                sx={{
                                    minWidth: 0,
                                    color: theme.palette.text.primary,
                                    fontSize: 13,
                                    fontWeight: 500,
                                    lineHeight: "22px",
                                    overflow: "hidden",
                                    textOverflow: "ellipsis",
                                    whiteSpace: {
                                        xs: "normal",
                                        md: "nowrap",
                                    },
                                }}
                            >
                                {row.ministry || "-"}
                            </Typography>
                        </Stack>
                    </MetaItem>
                </Box>

                <Box
                    sx={{
                        display: "grid",
                        gridTemplateColumns: {
                            xs: "1fr",
                            sm: "1fr 1fr",
                            lg: "1fr 1fr 1fr 1.25fr",
                        },
                        columnGap: {
                            xs: 2,
                            lg: 4,
                        },
                        rowGap: 2,
                        alignItems: "center",
                        py: 1.5,
                    }}
                >
                    <MetaItem
                        icon={<CalendarMonthOutlinedIcon />}
                        label={isKhmer ? "កាលបរិច្ឆេទប្រជុំ" : "Meeting Date"}
                    >
                        {row.meetingDate || "-"}
                    </MetaItem>

                    <MetaItem
                        icon={<LocalOfferOutlinedIcon />}
                        label={isKhmer ? "ប្រភេទ" : "Category"}
                    >
                        {row.category || "-"}
                    </MetaItem>

                    <MetaItem
                        icon={<ViewWeekOutlinedIcon />}
                        label={isKhmer ? "ស្ថានភាព" : "Status"}
                    >
                        <RgcDecisionStatusChip status={row.status} />
                    </MetaItem>

                    <MetaItem
                        icon={<PersonOutlineRoundedIcon />}
                        label={isKhmer ? "មន្ត្រីបង្គោល (ឯកឧត្តម)" : "Focal Person (H.E)"}
                    >
                        {row.focalPerson || "-"}
                    </MetaItem>
                </Box>

                <Divider />
            </Box>

            <Stack spacing={2}>
                <DetailField
                    label={isKhmer ? "បរិយាយបញ្ហា" : "Issues Description"}
                    value="-"
                />

                <DetailField
                    label={isKhmer ? "អនុសាសន៍" : "Recommendations"}
                    value="-"
                />

                <DetailField
                    label={isKhmer ? "សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល" : "RGC Decision"}
                    value={row.decision}
                    isRichText
                />

                <DetailField
                    label={isKhmer ? "សូចនាករ" : "Indicators"}
                    value={row.indicator}
                />

                <DetailField
                    label={isKhmer ? "វឌ្ឍនភាពនៃដំណោះស្រាយ" : "Progress Solution"}
                    value="-"
                />

                <DetailField
                    label={isKhmer ? "បញ្ហាប្រឈមក្នុងការអនុវត្ត" : "Implementation Challenges"}
                    value="-"
                />

                <DetailField
                    label={isKhmer ? "សំណើ" : "Request"}
                    value="-"
                />

                <DetailField
                    label={isKhmer ? "ជំហានបន្ទាប់" : "Next Step"}
                    value="-"
                />

                <DetailField
                    label={isKhmer ? "ប្រភពនៃការផ្ទៀងផ្ទាត់" : "Source of Verification"}
                    value={row.sourceOfVerification}
                    isRichText
                />

                <DetailField
                    label={isKhmer ? "តំណភ្ជាប់ប្រភពផ្ទៀងផ្ទាត់" : "Link to Verification Source"}
                    value={row.verificationLink}
                    isLink
                />
            </Stack>
        </Box>
    );
}

export default RgcDecisionDetailScreen;