"use client";

import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import CategoryOutlinedIcon from "@mui/icons-material/CategoryOutlined";
import DomainOutlinedIcon from "@mui/icons-material/DomainOutlined";
import InsertLinkRoundedIcon from "@mui/icons-material/InsertLinkRounded";
import PersonOutlineRoundedIcon from "@mui/icons-material/PersonOutlineRounded";
import ViewColumnOutlinedIcon from "@mui/icons-material/ViewColumnOutlined";

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

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

import type { MinistryRgcDecisionRow } from "../data/ministry-rgc-decision-data";
import { MinistryRgcDecisionStatusChip } from "../components/ministry-rgc-decision-status-chip";
import {
  ministryRgcDecisionText,
  normalizeMinistryRgcDecisionLanguage,
} from "../ministry-rgc-decision-i18n";

type Props = {
  decision: MinistryRgcDecisionRow;
  onBack: () => void;
};

type InformationFieldProps = {
  label: string;
  value?: React.ReactNode;
  minHeight?: number;
};

/**
 * Keeps the editor formatting in View Detail while removing unsafe content.
 * No external package is required.
 */
function sanitizeRichTextHtml(value: string | null | undefined): string {
  if (!value) {
    return "";
  }

  let html = String(value)
    .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "")
    .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, "")
    .replace(/<iframe\b[^>]*>[\s\S]*?<\/iframe>/gi, "")
    .replace(/<object\b[^>]*>[\s\S]*?<\/object>/gi, "")
    .replace(/<embed\b[^>]*\/?\s*>/gi, "")
    .replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "")
    .replace(/\s(href|src)\s*=\s*(["'])\s*javascript:[\s\S]*?\2/gi, "");

  // Decode once when the backend returns escaped HTML.
  if (/&lt;[a-z][\s\S]*&gt;/i.test(html)) {
    if (typeof document !== "undefined") {
      const textarea = document.createElement("textarea");
      textarea.innerHTML = html;
      html = textarea.value;
    } else {
      html = html
        .replace(/&lt;/gi, "<")
        .replace(/&gt;/gi, ">")
        .replace(/&quot;/gi, '"')
        .replace(/&#39;/gi, "'")
        .replace(/&amp;/gi, "&");
    }
  }

  return html;
}

function RichTextValue({ value }: { value: string | null | undefined }) {
  const safeHtml = sanitizeRichTextHtml(value);

  if (!safeHtml) {
    return <>-</>;
  }

  return (
    <Box
      component="div"
      dangerouslySetInnerHTML={{ __html: safeHtml }}
      sx={{
        width: "100%",
        minWidth: 0,
        "& p": { my: 0.5 },
        "& p:first-of-type": { mt: 0 },
        "& p:last-of-type": { mb: 0 },
        "& ul, & ol": { my: 0.5, pl: 3 },
        "& blockquote": {
          my: 0.5,
          ml: 0,
          pl: 1.5,
          borderLeft: "3px solid",
          borderColor: "divider",
          color: "text.secondary",
        },
        "& a": {
          color: "primary.main",
          textDecoration: "underline",
        },
        "& pre": {
          maxWidth: "100%",
          my: 0.5,
          p: 1,
          overflowX: "auto",
          borderRadius: 1,
          bgcolor: "action.hover",
          whiteSpace: "pre-wrap",
        },
      }}
    />
  );
}

function InformationField({
  label,
  value,
  minHeight = 54,
}: InformationFieldProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

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

      <Box
        sx={{
          minHeight,
          width: "100%",
          px: 1.5,
          py: 1.35,
          display: "flex",
          alignItems: "center",
          borderRadius: "7px",
          border: `1px solid ${theme.palette.divider}`,
          bgcolor: isDark
            ? alpha(theme.palette.common.white, 0.025)
            : "#FAFBFC",
          color: theme.palette.text.primary,
          fontSize: 13,
          fontWeight: 500,
          lineHeight: 1.7,
          whiteSpace: "pre-wrap",
          overflowWrap: "anywhere",
        }}
      >
        {value || "-"}
      </Box>
    </Box>
  );
}

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

  return (
    <Stack
      direction="row"
      spacing={1}
      sx={{
        minWidth: 0,
        alignItems: "center",
      }}
    >
      <Box
        sx={{
          display: "grid",
          placeItems: "center",
          flexShrink: 0,
          color: theme.palette.text.secondary,

          "& svg": {
            fontSize: 18,
          },
        }}
      >
        {icon}
      </Box>

      <Typography
        component="span"
        sx={{
          flexShrink: 0,
          color: theme.palette.text.secondary,
          fontSize: 13,
          fontWeight: 500,
        }}
      >
        {label}
      </Typography>

      <Box
        sx={{
          minWidth: 0,
          color: theme.palette.text.primary,
          fontSize: 13,
          fontWeight: 600,
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}
      >
        {children}
      </Box>
    </Stack>
  );
}

export function MinistryRgcDecisionDetailScreen({ decision, onBack }: Props) {
  const theme = useTheme();
  const { language } = useAppLanguage();
  const currentLanguage = normalizeMinistryRgcDecisionLanguage(language);
  const text = ministryRgcDecisionText[currentLanguage];

  const plenaryTitle =
    decision.plenaryName?.trim() ||
    (decision.plenaryId
      ? `${text.plenary} #${decision.plenaryId}`
      : text.plenary);

  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,
        overflowX: "hidden",
      }}
    >
      {/* Page heading */}
      <Stack
        direction={{
          xs: "column",
          sm: "row",
        }}
        spacing={{
          xs: 1.5,
          sm: 2.5,
        }}
        sx={{
          mb: 3,
          alignItems: {
            xs: "flex-start",
            sm: "flex-start",
          },
        }}
      >
        <Button
          variant="text"
          startIcon={<ArrowBackRoundedIcon />}
          onClick={onBack}
          sx={{
            minWidth: 0,
            mt: {
              xs: 0,
              sm: 0.2,
            },
            px: 0,
            color: theme.palette.text.secondary,
            textTransform: "none",
            fontSize: 13,
            fontWeight: 500,

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

            "& .MuiButton-startIcon": {
              mr: 0.75,
            },
          }}
        >
          {text.back}
        </Button>

        <Box>
          <Typography
            component="h1"
            sx={{
              color: theme.palette.text.primary,
              fontSize: {
                xs: 24,
                md: 28,
              },
              fontWeight: 800,
              lineHeight: 1.2,
            }}
          >
            {text.detailTitle}
          </Typography>

          <Typography
            sx={{
              mt: 0.8,
              color: theme.palette.text.secondary,
              fontSize: 13,
              fontWeight: 500,
            }}
          >
            {text.detailSubtitle}
          </Typography>
        </Box>
      </Stack>

      {/* Plenary and Ministry */}
      <Typography
        sx={{
          mb: 1.5,
          color: theme.palette.text.primary,
          fontSize: {
            xs: 25,
            md: 30,
          },
          fontWeight: 800,
          lineHeight: 1.2,
        }}
      >
        {plenaryTitle}
      </Typography>

      <Stack
        direction="row"
        spacing={1}
        sx={{
          mb: 3,
          alignItems: "center",
        }}
      >
        <DomainOutlinedIcon
          sx={{
            color: theme.palette.text.secondary,
            fontSize: 18,
          }}
        />

        <Typography
          sx={{
            color: theme.palette.text.secondary,
            fontSize: 13,
            fontWeight: 500,
          }}
        >
          {text.ministry}
        </Typography>

        <Avatar
          src={decision.ministryLogo || undefined}
          alt={decision.ministry || text.ministry}
          sx={{
            width: 24,
            height: 24,
            bgcolor: theme.palette.background.paper,
            color: theme.palette.primary.main,
            border: `1px solid ${theme.palette.primary.main}`,
            fontSize: 10,
            fontWeight: 800,
          }}
        >
          {decision.ministry?.trim().charAt(0).toUpperCase() || "M"}
        </Avatar>

        <Typography
          sx={{
            color: theme.palette.text.primary,
            fontSize: 13,
            fontWeight: 700,
          }}
        >
          {decision.ministry || "-"}
        </Typography>
      </Stack>

      {/* Metadata row */}
      <Box
        sx={{
          width: "100%",
          display: "grid",
          gridTemplateColumns: {
            xs: "1fr",
            sm: "repeat(2, minmax(0, 1fr))",
            xl: "repeat(4, minmax(0, 1fr))",
          },
          columnGap: 3,
          rowGap: 2,
          pb: 2.3,
          mb: 2.5,
          borderBottom: `1px solid ${theme.palette.divider}`,
        }}
      >
        <MetaItem icon={<CalendarMonthOutlinedIcon />} label={text.meetingDate}>
          {decision.meetingDate || "-"}
        </MetaItem>

        <MetaItem icon={<CategoryOutlinedIcon />} label={text.category}>
          {decision.category || "-"}
        </MetaItem>

        <MetaItem icon={<ViewColumnOutlinedIcon />} label={text.status}>
          <MinistryRgcDecisionStatusChip status={decision.status} />
        </MetaItem>

        <MetaItem icon={<PersonOutlineRoundedIcon />} label={text.focalPerson}>
          {decision.focalPerson || "-"}
        </MetaItem>
      </Box>

      {/* Detail fields */}
      <Stack spacing={2.2}>
        <InformationField
          label={text.issuesDescription}
          value={decision.issueDescription || "-"}
        />

        <InformationField
          label={text.recommendations}
          value={decision.recommendations || "-"}
        />

        <InformationField
          label={text.rgcDecision}
          value={<RichTextValue value={decision.decision} />}
        />

        <InformationField
          label={text.indicators}
          value={decision.indicators || decision.indicator || "-"}
        />

        <InformationField
          label={text.progressSolution}
          value={<RichTextValue value={decision.progressSolution} />}
        />

        <InformationField
          label={text.implementationChallenges}
          value={<RichTextValue value={decision.implementationChallenges} />}
        />

        <InformationField
          label={text.request}
          value={<RichTextValue value={decision.request} />}
        />

        <InformationField
          label={text.nextStep}
          value={<RichTextValue value={decision.nextStep} />}
        />

        <InformationField
          label={text.dateOfIssueSolution}
          value={decision.dateOfIssueSolution || "-"}
        />

        <InformationField
          label={text.attachment}
          value={
            decision.progressAttachment ? (
              <Link
                href={decision.progressAttachment}
                target="_blank"
                rel="noopener noreferrer"
                underline="always"
                sx={{
                  color: theme.palette.primary.main,
                  fontSize: 13,
                  fontWeight: 600,
                }}
              >
                {text.download}
              </Link>
            ) : (
              "-"
            )
          }
        />

        <InformationField
          label={text.sourceOfVerification}
          value={<RichTextValue value={decision.sourceOfVerification} />}
        />

        <InformationField
          label={text.verificationLink}
          value={
            decision.verificationLink ? (
              <Link
                href={decision.verificationLink}
                target="_blank"
                rel="noopener noreferrer"
                underline="always"
                sx={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 0.75,
                  color: theme.palette.primary.main,
                  fontSize: 13,
                  fontWeight: 600,
                  overflowWrap: "anywhere",
                }}
              >
                <InsertLinkRoundedIcon sx={{ fontSize: 16 }} />
                {decision.verificationLink}
              </Link>
            ) : (
              "-"
            )
          }
        />
      </Stack>

      <Box sx={{ height: 24 }} />
    </Box>
  );
}

export default MinistryRgcDecisionDetailScreen;
