"use client";

import type { ReactNode } from "react";

import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import CategoryOutlinedIcon from "@mui/icons-material/CategoryOutlined";
import CheckCircleOutlineRoundedIcon from "@mui/icons-material/CheckCircleOutlineRounded";
import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined";
import LinkRoundedIcon from "@mui/icons-material/LinkRounded";
import PersonOutlineRoundedIcon from "@mui/icons-material/PersonOutlineRounded";
import TrackChangesRoundedIcon from "@mui/icons-material/TrackChangesRounded";

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 { formatNumber } from "@/lib/number-utils";

export type ViewDetailRgcDecisionIssue = {
    id?: number | string;
    title?: string | null;
    name?: string | null;
    description?: string | null;
};

export type ViewDetailRgcDecisionRow = {
    id: number;

    ministryName: string;
    ministryLogo: string | null;

    decision: string;
    meetingDate: string;
    category: string;
    status: "Not Addressed" | "In Progress" | "Solved" | string;
    indicator: string;
    focalPerson: string;
    sourceOfVerification: string;
    verificationLink: string;

    issues?: ViewDetailRgcDecisionIssue[];
};

type ViewDetailRgcDecisionProps = {
    row: ViewDetailRgcDecisionRow;
    onBack: () => void;
};

type DetailItemProps = {
    icon: ReactNode;
    label: string;
    children: ReactNode;
};

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

const BACKEND_ORIGIN = API_BASE_URL.replace(
    /\/api\/v1\/?$/,
    "",
);

const KHMER_MONTHS = [
    "មករា",
    "កុម្ភៈ",
    "មីនា",
    "មេសា",
    "ឧសភា",
    "មិថុនា",
    "កក្កដា",
    "សីហា",
    "កញ្ញា",
    "តុលា",
    "វិច្ឆិកា",
    "ធ្នូ",
] as const;

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

    if (!source) {
        return undefined;
    }

    if (
        source.startsWith("http://") ||
        source.startsWith("https://") ||
        source.startsWith("data:") ||
        source.startsWith("blob:")
    ) {
        return source;
    }

    return `${BACKEND_ORIGIN}${
        source.startsWith("/") ? "" : "/"
    }${source}`;
}

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

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

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

    if (!match) {
        return formatNumber(raw, "kh");
    }

    const year = Number(match[1]);
    const monthIndex = Number(match[2]) - 1;
    const day = Number(match[3]);

    const month = KHMER_MONTHS[monthIndex];

    if (!month) {
        return formatNumber(raw, "kh");
    }

    return `${formatNumber(
        day,
        "kh",
    )} ${month} ${formatNumber(
        year,
        "kh",
    )}`;
}

function stripHtml(value: string | null | undefined): string {
    if (!value) {
        return "-";
    }

    return value
        .replace(/<br\s*\/?>/gi, "\n")
        .replace(/<\/p>/gi, "\n")
        .replace(/<\/div>/gi, "\n")
        .replace(/<[^>]*>/g, " ")
        .replace(/&nbsp;/gi, " ")
        .replace(/&amp;/gi, "&")
        .replace(/&lt;/gi, "<")
        .replace(/&gt;/gi, ">")
        .replace(/[ \t]+\n/g, "\n")
        .replace(/\n{3,}/g, "\n\n")
        .trim() || "-";
}

function isSafeHttpUrl(value: string): boolean {
    try {
        const url = new URL(value);

        return (
            url.protocol === "http:" ||
            url.protocol === "https:"
        );
    } catch {
        return false;
    }
}

function normalizeStatus(
    value: string,
): "Not Addressed" | "In Progress" | "Solved" {
    const normalized = String(value ?? "")
        .trim()
        .toUpperCase()
        .replace(/[\s-]+/g, "_");

    if (normalized === "SOLVED") {
        return "Solved";
    }

    if (normalized === "IN_PROGRESS") {
        return "In Progress";
    }

    return "Not Addressed";
}

function StatusChip({
    value,
    label,
}: {
    value: string;
    label: string;
}) {
    const theme = useTheme();
    const status = normalizeStatus(value);

    const style =
        status === "Solved"
            ? {
                color: "#16A34A",
                border: "#86EFAC",
                background: "#F0FDF4",
            }
            : status === "In Progress"
                ? {
                    color: "#D97706",
                    border: "#FCD34D",
                    background: "#FFFBEB",
                }
                : {
                    color: "#EF4444",
                    border: "#FCA5A5",
                    background: "#FEF2F2",
                };

    return (
        <Box
            component="span"
            sx={{
                minWidth: 104,
                height: 24,
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                px: 1.4,
                border: `1px solid ${style.border}`,
                borderRadius: 99,
                color: style.color,
                bgcolor:
                    theme.palette.mode === "dark"
                        ? alpha(style.color, 0.16)
                        : style.background,
                fontSize: 11,
                fontWeight: 700,
                whiteSpace: "nowrap",
            }}
        >
            {label}
        </Box>
    );
}

function MinistryAvatar({
    name,
    logo,
}: {
    name: string;
    logo: string | null;
}) {
    const theme = useTheme();
    const letter = name.trim().charAt(0).toUpperCase() || "M";

    if (logo) {
        return (
            <Avatar
                src={resolveMinistryLogoUrl(logo)}
                alt={name}
                sx={{
                    width: 28,
                    height: 28,
                    border: "1px solid",
                    borderColor: "divider",
                }}
            />
        );
    }

    return (
        <Avatar
            sx={{
                width: 28,
                height: 28,
                color: theme.palette.primary.main,
                bgcolor: alpha(theme.palette.primary.main, 0.12),
                border: `1px solid ${alpha(
                    theme.palette.primary.main,
                    0.35,
                )}`,
                fontSize: 11,
                fontWeight: 800,
            }}
        >
            {letter}
        </Avatar>
    );
}

function DetailItem({
    icon,
    label,
    children,
}: DetailItemProps) {
    return (
        <Stack
            direction="row"
            spacing={1}
            sx={{
                minWidth: 0,
                alignItems: "center",
            }}
        >
            <Box
                sx={{
                    display: "inline-flex",
                    flexShrink: 0,
                    color: "text.secondary",
                }}
            >
                {icon}
            </Box>

            <Typography
                sx={{
                    flexShrink: 0,
                    color: "text.secondary",
                    fontSize: 13,
                    whiteSpace: "nowrap",
                }}
            >
                {label}
            </Typography>

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

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

    return (
        <Box>
            <Typography
                sx={{
                    mb: 1,
                    color: "text.primary",
                    fontSize: 14,
                    fontWeight: 700,
                }}
            >
                {label}
            </Typography>

            <Paper
                elevation={0}
                sx={{
                    minHeight: 56,
                    px: 1.75,
                    py: 1.35,
                    border: "1px solid",
                    borderColor: "divider",
                    borderRadius: 1.5,
                    bgcolor:
                        theme.palette.mode === "dark"
                            ? alpha("#FFFFFF", 0.035)
                            : "#F8FAFC",
                }}
            >
                {children}
            </Paper>
        </Box>
    );
}

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

    const fontFamily = isKhmer
        ? '"Battambang", "Kantumruy Pro", sans-serif'
        : '"Inter", "Segoe UI", Arial, sans-serif';

    const text = isKhmer
        ? {
            back: "ត្រឡប់ក្រោយ",
            title: "ព័ត៌មានលម្អិតសេចក្តីសម្រេច RGC",
            subtitle: "ព័ត៌មានលម្អិតនៃសេចក្តីសម្រេច RGC",
            ministry: "ក្រសួង/ស្ថាប័ន",
            meetingDate: "កាលបរិច្ឆេទកិច្ចប្រជុំ",
            category: "ប្រភេទ",
            status: "ស្ថានភាព",
            focalPerson: "បុគ្គលទទួលបន្ទុក (ឯកឧត្តម)",
            linkedIssues: "បញ្ហាដែលបានភ្ជាប់",
            decision: "សេចក្តីសម្រេច RGC",
            indicator: "សូចនាករ",
            verificationSource: "ប្រភពផ្ទៀងផ្ទាត់",
            verificationLink: "តំណភ្ជាប់ប្រភពផ្ទៀងផ្ទាត់",
            viewSource: "មើលប្រភព",
            solved: "បានដោះស្រាយ",
            inProgress: "កំពុងដំណើរការ",
            notAddressed: "មិនទាន់ដោះស្រាយ",
            noData: "-",
        }
        : {
            back: "Back",
            title: "RGC Decision Detail",
            subtitle: "Detail Information of RGC Decision",
            ministry: "Ministry",
            meetingDate: "Meeting Date",
            category: "Category",
            status: "Status",
            focalPerson: "Focal Person (H.E)",
            linkedIssues: "Linked Issues",
            decision: "RGC Decision",
            indicator: "Indicator",
            verificationSource: "Source of Verification",
            verificationLink: "Link to Verification Source",
            viewSource: "View Source",
            solved: "Solved",
            inProgress: "In Progress",
            notAddressed: "Not Addressed",
            noData: "-",
        };

    const normalizedStatus = normalizeStatus(row.status);

    const statusLabel =
        normalizedStatus === "Solved"
            ? text.solved
            : normalizedStatus === "In Progress"
                ? text.inProgress
                : text.notAddressed;

    const issuesText =
        Array.isArray(row.issues) && row.issues.length > 0
            ? row.issues
                .map((item) =>
                    item.title?.trim() ||
                    item.name?.trim() ||
                    "",
                )
                .filter(Boolean)
                .join(", ")
            : text.noData;

    const verificationLinkIsUrl =
        Boolean(row.verificationLink) &&
        isSafeHttpUrl(row.verificationLink);

    return (
        <Box
            sx={{
                minHeight: "100vh",
                p: {
                    xs: 2,
                    sm: 3,
                    md: 4,
                },
                bgcolor: "background.default",
                color: "text.primary",
                fontFamily,

                "& .MuiTypography-root, & .MuiButton-root": {
                    fontFamily,
                },
            }}
        >
            {/* ================================================================ */}
            {/* HEADER                                                           */}
            {/* ================================================================ */}

            <Stack
                direction="row"
                spacing={2.5}
                sx={{
                    mb: {
                        xs: 4,
                        md: 5,
                    },
                    alignItems: "center",
                }}
            >
                <Button
                    startIcon={
                        <ArrowBackRoundedIcon
                            sx={{
                                fontSize: 18,
                            }}
                        />
                    }
                    onClick={onBack}
                    sx={{
                        minWidth: 0,
                        px: 0,
                        color: "text.secondary",
                        textTransform: "none",
                        fontSize: 14,
                        fontWeight: 500,

                        "&:hover": {
                            bgcolor: "transparent",
                            color: "primary.main",
                        },
                    }}
                >
                    {text.back}
                </Button>

                <Box>
                    <Typography
                        sx={{
                            fontSize: {
                                xs: isKhmer ? 20 : 20,
                                md: isKhmer ? 21 : 22,
                            },
                            lineHeight: isKhmer ? 1.55 : 1.2,
                            fontWeight: 700,
                        }}
                    >
                        {text.title}
                    </Typography>

                    <Typography
                        sx={{
                            mt: 0.4,
                            color: "text.secondary",
                            fontSize: 13,
                        }}
                    >
                        {text.subtitle}
                    </Typography>
                </Box>
            </Stack>

            {/* ================================================================ */}
            {/* MAIN DECISION TITLE                                              */}
            {/* ================================================================ */}

            <Typography
                sx={{
                    mb: 2.5,
                    color: "text.primary",
                    fontSize: {
                        xs: 24,
                        md: 28,
                    },
                    fontWeight: 800,
                }}
            >
                {stripHtml(row.decision)}
            </Typography>

            {/* ================================================================ */}
            {/* MINISTRY                                                         */}
            {/* ================================================================ */}

            <DetailItem
                icon={<PersonOutlineRoundedIcon fontSize="small" />}
                label={text.ministry}
            >
                <Stack
                    direction="row"
                    spacing={1}
                    sx={{
                        alignItems: "center",
                    }}
                >
                    <MinistryAvatar
                        name={row.ministryName}
                        logo={row.ministryLogo}
                    />

                    <Typography
                        sx={{
                            color: "text.primary",
                            fontSize: 13,
                            fontWeight: 700,
                        }}
                    >
                        {row.ministryName || text.noData}
                    </Typography>
                </Stack>
            </DetailItem>

            <Divider
                sx={{
                    my: 2.6,
                }}
            />

            {/* ================================================================ */}
            {/* TOP FIELDS - SAME AS TABLE COLUMNS                               */}
            {/* ================================================================ */}

            <Box
                sx={{
                    display: "grid",
                    gridTemplateColumns: {
                        xs: "1fr",
                        sm: "repeat(2, minmax(0, 1fr))",
                        xl: "repeat(4, minmax(0, 1fr))",
                    },
                    columnGap: 4,
                    rowGap: 2.25,
                    mb: 3,
                }}
            >
                <DetailItem
                    icon={<CalendarMonthOutlinedIcon fontSize="small" />}
                    label={text.meetingDate}
                >
                    <Typography
                        sx={{
                            fontSize: 13,
                            fontWeight: 700,
                        }}
                    >
                        {isKhmer
                            ? formatKhmerMeetingDate(
                                row.meetingDate,
                            )
                            : row.meetingDate || text.noData}
                    </Typography>
                </DetailItem>

                <DetailItem
                    icon={<CategoryOutlinedIcon fontSize="small" />}
                    label={text.category}
                >
                    <Typography
                        sx={{
                            fontSize: 13,
                            fontWeight: 700,
                        }}
                    >
                        {row.category || text.noData}
                    </Typography>
                </DetailItem>

                <DetailItem
                    icon={<CheckCircleOutlineRoundedIcon fontSize="small" />}
                    label={text.status}
                >
                    <StatusChip
                        value={row.status}
                        label={statusLabel}
                    />
                </DetailItem>

                <DetailItem
                    icon={<PersonOutlineRoundedIcon fontSize="small" />}
                    label={text.focalPerson}
                >
                    <Typography
                        sx={{
                            minWidth: 0,
                            overflow: "hidden",
                            fontSize: 13,
                            fontWeight: 700,
                            textOverflow: "ellipsis",
                            whiteSpace: "nowrap",
                        }}
                    >
                        {row.focalPerson || text.noData}
                    </Typography>
                </DetailItem>
            </Box>

            <Divider sx={{ mb: 3 }} />

            {/* ================================================================ */}
            {/* DETAIL SECTIONS - BASED ON TABLE COLUMNS                         */}
            {/* ================================================================ */}

            <Stack spacing={2.25}>
                <DetailSection label={text.linkedIssues}>
                    <Typography
                        sx={{
                            whiteSpace: "pre-wrap",
                            fontSize: 13,
                            lineHeight: 1.7,
                        }}
                    >
                        {issuesText}
                    </Typography>
                </DetailSection>

                <DetailSection label={text.decision}>
                    <Typography
                        sx={{
                            whiteSpace: "pre-wrap",
                            fontSize: 13,
                            lineHeight: 1.7,
                        }}
                    >
                        {stripHtml(row.decision)}
                    </Typography>
                </DetailSection>

                <DetailSection label={text.indicator}>
                    <Stack
                        direction="row"
                        spacing={1}
                        sx={{
                            alignItems: "center",
                        }}
                    >
                        <TrackChangesRoundedIcon
                            sx={{
                                color: "text.secondary",
                                fontSize: 18,
                            }}
                        />

                        <Typography
                            sx={{
                                fontSize: 13,
                                lineHeight: 1.7,
                            }}
                        >
                            {row.indicator || text.noData}
                        </Typography>
                    </Stack>
                </DetailSection>

                <DetailSection label={text.verificationSource}>
                    <Stack
                        direction="row"
                        spacing={1}
                        sx={{
                            alignItems: "flex-start",
                        }}
                    >
                        <DescriptionOutlinedIcon
                            sx={{
                                mt: 0.15,
                                flexShrink: 0,
                                color: "text.secondary",
                                fontSize: 18,
                            }}
                        />

                        <Typography
                            sx={{
                                whiteSpace: "pre-wrap",
                                fontSize: 13,
                                lineHeight: 1.7,
                            }}
                        >
                            {stripHtml(row.sourceOfVerification)}
                        </Typography>
                    </Stack>
                </DetailSection>

                <DetailSection label={text.verificationLink}>
                    <Stack
                        direction="row"
                        spacing={1}
                        sx={{
                            minWidth: 0,
                            alignItems: "center",
                        }}
                    >
                        <LinkRoundedIcon
                            sx={{
                                flexShrink: 0,
                                color: "text.secondary",
                                fontSize: 18,
                            }}
                        />

                        {verificationLinkIsUrl ? (
                            <Link
                                href={row.verificationLink}
                                target="_blank"
                                rel="noopener noreferrer"
                                underline="always"
                                title={row.verificationLink}
                                sx={{
                                    minWidth: 0,
                                    overflow: "hidden",
                                    color: theme.palette.primary.main,
                                    fontSize: 13,
                                    fontWeight: 700,
                                    textOverflow: "ellipsis",
                                    whiteSpace: "nowrap",
                                }}
                            >
                                {row.verificationLink}
                            </Link>
                        ) : (
                            <Typography
                                sx={{
                                    color: "text.secondary",
                                    fontSize: 13,
                                }}
                            >
                                {text.noData}
                            </Typography>
                        )}
                    </Stack>
                </DetailSection>
            </Stack>
        </Box>
    );
}

export default ViewDetailRgcDecision;