"use client";

import type { ReactNode } from "react";

import Box from "@mui/material/Box";
import Dialog from "@mui/material/Dialog";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { AppDivider } from "@/components/ui/divider";
import {
  CategoryOfIssuesIcon,
  GovernmentAgencyIcon,
  SubmitDateIcon,
  WarningIcon,
} from "@/components/ui/icon";
import { IssueStatusBadge } from "@/components/ui/issue-status-badge";
import {
  cdcGpsfMeetingRequestI18n,
  getCdcGpsfMeetingRequestFont,
  type CdcGpsfMeetingRequestUiLang,
} from "@/features/cdc-gpsf/meeting-requests/cdc-gpsf-meeting-request-i18n";
import {
  resolveAssetUrl,
  type ApiIssue,
  type ApiMeetingRequest,
} from "@/features/cdc-gpsf/meeting-requests/service/cdc-gpsf-meeting-request-service";

type CdcGpsfMeetingRequestIssueDetailDialogProps = {
  open: boolean;
  issue: ApiIssue | null;
  meetingRequest: ApiMeetingRequest | null;
  language?: CdcGpsfMeetingRequestUiLang;
  onClose: () => void;
};

function formatDate(value?: string | null) {
  if (!value) return "-";

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) return "-";

  return date.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

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

  return (
    value
      .replace(/<br\s*\/?>/gi, "\n")
      .replace(/<\/p>/gi, "\n")
      .replace(/<[^>]*>/g, "")
      .replace(/\n{3,}/g, "\n\n")
      .trim() || "-"
  );
}

function isKhmerText(value?: string | null) {
  if (!value) return false;
  return /[\u1780-\u17FF]/.test(value);
}

const META_LABEL_VALUE_GAP = 24;

function MetaLabel({ children }: { children: ReactNode }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Typography
      sx={{
        color: isDark ? "#d0d5dd" : "#717680",
        fontSize: 13,
        fontWeight: 400,
        lineHeight: "22px",
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </Typography>
  );
}

function MetaFieldsGrid({
  fields,
}: {
  fields: Array<{
    icon: ReactNode;
    label: string;
    value: ReactNode;
    align?: "center" | "start";
  }>;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: "20px max-content minmax(min-content, 1fr)",
        columnGap: "11px",
        rowGap: "16px",
        alignItems: "center",
      }}
    >
      {fields.flatMap((field, index) => {
        const alignSelf = field.align === "start" ? "start" : "center";

        return [
          <Box
            key={`${index}-icon`}
            sx={{
              color: isDark ? "#98a2b3" : "#717680",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              alignSelf,
              pt: field.align === "start" ? "1px" : 0,
            }}
          >
            {field.icon}
          </Box>,
          <Box
            key={`${index}-label`}
            sx={{ alignSelf, pr: `${META_LABEL_VALUE_GAP}px` }}
          >
            <MetaLabel>{field.label} :</MetaLabel>
          </Box>,
          <Box
            key={`${index}-value`}
            sx={{
              minWidth: 0,
              display: "flex",
              alignItems: "center",
              alignSelf,
            }}
          >
            {field.value}
          </Box>,
        ];
      })}
    </Box>
  );
}

function MetaValue({ children }: { children: ReactNode }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const text = typeof children === "string" ? children : undefined;

  return (
    <Typography
      title={text}
      sx={{
        color: isDark ? "#f9fafb" : "#252b37",
        fontSize: 13,
        fontWeight: 500,
        lineHeight: "22px",
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </Typography>
  );
}

function AgencyValue({
  name,
  logo,
}: {
  name?: string | null;
  logo?: string | null;
}) {
  const logoUrl = resolveAssetUrl(logo);
  const value = name?.trim() || "-";

  return (
    <Box
      sx={{ display: "flex", alignItems: "center", gap: "8px", minWidth: 0 }}
    >
      {logoUrl ? (
        <Box
          component="img"
          src={logoUrl}
          alt={value}
          sx={{
            width: 19,
            height: 19,
            borderRadius: "50%",
            objectFit: "cover",
            flexShrink: 0,
          }}
        />
      ) : null}
      <Typography
        noWrap
        sx={{
          fontSize: 13,
          fontWeight: 500,
          color: "inherit",
          lineHeight: 1.2,
        }}
      >
        {value}
      </Typography>
    </Box>
  );
}

function TextSection({
  title,
  content,
  fontFamily,
  isKhmer,
}: {
  title: string;
  content: string;
  fontFamily: string;
  isKhmer: boolean;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: "12px" }}>
      <Typography
        sx={{
          fontSize: 16,
          fontWeight: 700,
          color: isDark ? "#f9fafb" : "#252b37",
          fontFamily,
        }}
      >
        {title}
      </Typography>

      <Typography
        component="div"
        className={isKhmer ? "font-kh" : undefined}
        sx={{
          p: "16px",
          borderRadius: "12px",
          bgcolor: isDark ? alpha("#ffffff", 0.04) : "#f5f5f5",
          color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
          fontSize: 13,
          fontWeight: 400,
          lineHeight: "22px",
          whiteSpace: "pre-wrap",
          fontFamily,
        }}
      >
        {content}
      </Typography>
    </Box>
  );
}

export function CdcGpsfMeetingRequestIssueDetailDialog({
  open,
  issue,
  meetingRequest,
  language = "km",
  onClose,
}: CdcGpsfMeetingRequestIssueDetailDialogProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const t = cdcGpsfMeetingRequestI18n(language);
  const fontFamily = getCdcGpsfMeetingRequestFont(language);

  if (!issue) return null;

  const firstAgency = meetingRequest?.governmentAgencies?.[0]?.stakeholder;
  const issueTitle = issue.title || "-";
  const descriptionText = stripHtml(issue.description);
  const recommendationText = stripHtml(issue.recommendation);
  const classification = issue.category?.name || "-";
  const issueStatus =
    issue.issueStatus?.name || meetingRequest?.status || "Submitted";
  const submittedDate = formatDate(
    issue.createdAt || meetingRequest?.createdAt,
  );
  const titleIsKhmer = isKhmerText(issueTitle) || language === "km";
  const descriptionIsKhmer = isKhmerText(descriptionText) || language === "km";
  const recommendationIsKhmer =
    isKhmerText(recommendationText) || language === "km";

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth={false}
      scroll="paper"
      sx={{
        zIndex: 1700,
        "& .MuiBackdrop-root": { bgcolor: "rgba(0,0,0,0.45)" },
      }}
      slotProps={{
        paper: {
          sx: {
            width: { xs: "calc(100vw - 32px)", md: 675, lg: 820 },
            maxWidth: "calc(100vw - 32px)",
            maxHeight: "calc(100dvh - 34px)",
            borderRadius: "12px",
            overflow: "hidden",
            bgcolor: isDark ? "#101828" : "#ffffff",
            backgroundImage: "none",
            fontFamily,
          },
        },
      }}
    >
      <Box
        sx={{
          height: 70,
          px: 2.75,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 2,
        }}
      >
        <Typography
          className={titleIsKhmer ? "font-kh" : undefined}
          sx={{
            pr: 2,
            fontSize: 20,
            fontWeight: 500,
            letterSpacing: "-0.4px",
            color: isDark ? "#f9fafb" : "#181d27",
            lineHeight: 1.25,
          }}
        >
          {issueTitle}
        </Typography>

        <IconButton
          onClick={onClose}
          aria-label="Close"
          size="small"
          sx={{ color: isDark ? "#d0d5dd" : "#717680", flexShrink: 0 }}
        >
          ✕
        </IconButton>
      </Box>

      <AppDivider />

      <Box
        sx={{
          px: 2.75,
          py: 2.75,
          overflowY: "auto",
          maxHeight: "calc(100dvh - 120px)",
          display: "flex",
          flexDirection: "column",
          gap: "22px",
        }}
      >
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
            columnGap: "32px",
            rowGap: "16px",
            alignItems: "start",
          }}
        >
          <Box sx={{ minWidth: 0 }}>
            <MetaFieldsGrid
              fields={[
                {
                  icon: <GovernmentAgencyIcon sx={{ fontSize: 20 }} />,
                  label: t.governmentAgency,
                  value: (
                    <AgencyValue
                      name={firstAgency?.name}
                      logo={firstAgency?.logo}
                    />
                  ),
                },
                {
                  icon: <CategoryOfIssuesIcon sx={{ fontSize: 20 }} />,
                  label: t.classification,
                  value: <MetaValue>{classification}</MetaValue>,
                },
              ]}
            />
          </Box>

          <Box sx={{ minWidth: 0 }}>
            <MetaFieldsGrid
              fields={[
                {
                  icon: <SubmitDateIcon sx={{ fontSize: 20 }} />,
                  label: t.submittedDate,
                  value: <MetaValue>{submittedDate}</MetaValue>,
                },
                {
                  icon: <WarningIcon sx={{ fontSize: 18 }} />,
                  label: t.status,
                  value: <IssueStatusBadge status={issueStatus} />,
                },
              ]}
            />
          </Box>
        </Box>

        <AppDivider />

        <TextSection
          title={t.issueDescription}
          content={descriptionText}
          fontFamily={fontFamily}
          isKhmer={descriptionIsKhmer}
        />

        <TextSection
          title={t.recommendation}
          content={recommendationText}
          fontFamily={fontFamily}
          isKhmer={recommendationIsKhmer}
        />
      </Box>
    </Dialog>
  );
}
