"use client";

import { useEffect, useMemo, useState, type ReactNode } from "react";

import CloseIcon from "@mui/icons-material/Close";
import Box from "@mui/material/Box";
import CircularProgress from "@mui/material/CircularProgress";
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 { useAppLanguage } from "@/components/providers/app-language-provider";
import { DocumentLink } from "@/components/ui/document-link";
import { DocumentFileAttachment } from "@/components/ui/document-file-name";
import { MeetingRequestStatusBadge } from "@/components/ui/meeting-request-status-badge";
import { isDocumentPlaceholder } from "@/lib/document-file";
import {
  getMeetingRequestFont,
  i18n,
  type UiLang,
} from "@/features/pswg/meeting-request/meeting-request-i18n";
import {
  meetingRequestService,
  resolveAssetUrl,
  type ApiMeetingRequest,
  type MeetingRequestStatus,
} from "@/features/pswg/meeting-request/service/meeting-request-service";

type MeetingRequestDetailDialogProps = {
  open: boolean;
  meetingRequestId: number | null;
  onClose: () => void;
};

function normalizeLanguage(language?: string): UiLang {
  if (language === "en") return "en";
  return "km";
}

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

function LineIcon({
  type,
  size = 20,
}: {
  type: "calendar" | "user" | "status" | "link";
  size?: number;
}) {
  const common = {
    width: size,
    height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 1.8,
    strokeLinecap: "round" as const,
    strokeLinejoin: "round" as const,
  };

  if (type === "calendar") {
    return (
      <Box component="svg" {...common}>
        <path d="M8 2v4" />
        <path d="M16 2v4" />
        <rect x="3" y="4" width="18" height="18" rx="2" />
        <path d="M3 10h18" />
      </Box>
    );
  }

  if (type === "user") {
    return (
      <Box component="svg" {...common}>
        <path d="M20 21a8 8 0 0 0-16 0" />
        <circle cx="12" cy="7" r="4" />
      </Box>
    );
  }

  if (type === "link") {
    return (
      <Box component="svg" {...common}>
        <path d="M10 13a5 5 0 0 0 7.07 0l2.12-2.12a5 5 0 0 0-7.07-7.07L11 4.93" />
        <path d="M14 11a5 5 0 0 0-7.07 0L4.81 13.12a5 5 0 0 0 7.07 7.07L13 19.07" />
      </Box>
    );
  }

  return (
    <Box
      component="svg"
      width={18}
      height={18}
      viewBox="0 0 24 24"
      fill="none"
      sx={{ display: "block", flexShrink: 0 }}
    >
      <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.4" />
      <path
        d="M12 8v5"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
      />
      <circle cx="12" cy="16" r="0.75" fill="currentColor" />
    </Box>
  );
}

function MetaLabel({ children }: { children: ReactNode }) {
  return (
    <Typography
      sx={{
        color: "#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";
  }>;
}) {
  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: "20px max-content minmax(0, 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: "#717680",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              alignSelf,
              pt: field.align === "start" ? "1px" : 0,
            }}
          >
            {field.icon}
          </Box>,
          <Box
            key={`${index}-label`}
            sx={{ alignSelf }}
          >
            <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 }) {
  return (
    <Typography
      sx={{
        color: "#252b37",
        fontSize: 13,
        fontWeight: 500,
        lineHeight: 1.2,
      }}
    >
      {children}
    </Typography>
  );
}

function AgencyInfo({ data }: { data: ApiMeetingRequest }) {
  const firstAgency = data.governmentAgencies?.[0]?.stakeholder;
  const logoUrl = resolveAssetUrl(firstAgency?.logo);

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: "8px", minWidth: 0 }}>
      {logoUrl ? (
        <Box
          component="img"
          src={logoUrl}
          alt={firstAgency?.name || "Agency"}
          sx={{
            width: 19,
            height: 19,
            borderRadius: "50%",
            objectFit: "cover",
            flexShrink: 0,
          }}
        />
      ) : null}

      <Typography
        noWrap
        sx={{ color: "#252b37", fontSize: 13, fontWeight: 500, lineHeight: 1.2 }}
      >
        {firstAgency?.name || "-"}
      </Typography>
    </Box>
  );
}

function MeetingRequestDocument({ path }: { path?: string | null }) {
  if (isDocumentPlaceholder(path) || !path) {
    return <MetaValue>-</MetaValue>;
  }

  return (
    <DocumentLink
      file={{ path }}
      sx={{
        display: "inline-flex",
        alignItems: "center",
        minWidth: 0,
      }}
    >
      <DocumentFileAttachment value={path} emptyLabel="-" iconSize={20} />
    </DocumentLink>
  );
}

function IssueCountBadge({ count }: { count: number }) {
  return (
    <Box
      sx={{
        minWidth: 28,
        height: 21,
        px: "10px",
        borderRadius: "6px",
        border: "1px solid #fee4e2",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Typography
        sx={{
          color: "#f04438",
          fontSize: 12,
          fontWeight: 500,
          lineHeight: 1,
        }}
      >
        {count}
      </Typography>
    </Box>
  );
}

export function MeetingRequestDetailDialog({
  open,
  meetingRequestId,
  onClose,
}: MeetingRequestDetailDialogProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const { language } = useAppLanguage();
  const uiLang = normalizeLanguage(language);
  const t = i18n(uiLang);
  const fontFamily = getMeetingRequestFont(uiLang);

  const [data, setData] = useState<ApiMeetingRequest | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const issues = useMemo(() => data?.issues || [], [data]);
  const descriptionText = useMemo(
    () => stripHtml(data?.description) || "-",
    [data?.description],
  );

  const statusLabel =
    data?.status && t.statuses[data.status as MeetingRequestStatus]
      ? t.statuses[data.status as MeetingRequestStatus]
      : data?.status;

  useEffect(() => {
    let active = true;

    async function fetchDetail() {
      if (!open || !meetingRequestId) return;

      try {
        setLoading(true);
        setError(null);
        setData(null);

        const result = await meetingRequestService.getById(meetingRequestId);

        if (!active) return;

        setData(result);
      } catch (err) {
        if (!active) return;

        setError(
          err instanceof Error
            ? err.message
            : "Failed to load meeting request detail",
        );
      } finally {
        if (active) {
          setLoading(false);
        }
      }
    }

    void fetchDetail();

    return () => {
      active = false;
    };
  }, [open, meetingRequestId]);

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth={false}
      slotProps={{
        backdrop: {
          sx: {
            bgcolor: alpha("#000000", 0.58),
          },
        },
        paper: {
          sx: {
            width: 642,
            maxWidth: "calc(100vw - 32px)",
            maxHeight: "calc(100vh - 40px)",
            borderRadius: "6px",
            overflow: "hidden",
            bgcolor: isDark ? "#101828" : "#ffffff",
            boxShadow: "0px 24px 60px rgba(16, 24, 40, 0.28)",
            fontFamily,
          },
        },
      }}
    >
      <Box
        sx={{
          position: "relative",
          px: "22px",
          pt: "33px",
          pb: 0,
          minHeight: 118,
          borderBottom: `1px solid ${isDark ? alpha("#ffffff", 0.08) : "#f5f5f5"}`,
        }}
      >
        <Typography
          className={
            isKhmerText(data?.title) || uiLang === "km" ? "font-kh" : undefined
          }
          sx={{
            color: isDark ? "#ffffff" : "#181d27",
            fontSize: 18,
            fontWeight: 600,
            lineHeight: 1.2,
            letterSpacing: "-0.36px",
            pr: 5,
          }}
        >
          {data?.title || "Meeting Request Detail"}
        </Typography>

        <IconButton
          onClick={onClose}
          aria-label="Close"
          sx={{
            position: "absolute",
            top: 32,
            right: 22,
            width: 24,
            height: 24,
            color: isDark ? alpha("#ffffff", 0.7) : "#717680",
          }}
        >
          <CloseIcon sx={{ fontSize: 24 }} />
        </IconButton>

        <Box
          sx={{
            display: "inline-flex",
            mt: "35px",
            pb: 1.5,
            borderBottom: "2px solid #1a64a8",
          }}
        >
          <Typography
            sx={{
              color: "#1a64a8",
              fontSize: 12,
              fontWeight: 500,
              lineHeight: 1,
            }}
          >
            {t.requestDetails}
          </Typography>
        </Box>
      </Box>

      <Box
        sx={{
          px: "20px",
          py: "20px",
          overflowY: "auto",
          maxHeight: "calc(100vh - 180px)",
        }}
      >
        {loading ? (
          <Box sx={{ minHeight: 320, display: "grid", placeItems: "center" }}>
            <CircularProgress size={26} />
          </Box>
        ) : null}

        {!loading && error ? (
          <Box sx={{ minHeight: 220, display: "grid", placeItems: "center" }}>
            <Typography sx={{ color: "#f04438", fontSize: 13 }}>{error}</Typography>
          </Box>
        ) : null}

        {!loading && !error && data ? (
          <Box sx={{ display: "flex", flexDirection: "column", gap: "22px" }}>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
                columnGap: { xs: 0, md: "22px" },
                rowGap: { xs: "16px", md: 0 },
              }}
            >
              <MetaFieldsGrid
                fields={[
                  {
                    icon: <LineIcon type="calendar" />,
                    label: t.submittedDate,
                    value: <MetaValue>{formatDate(data.createdAt)}</MetaValue>,
                  },
                  {
                    icon: <LineIcon type="status" size={18} />,
                    label: t.status,
                    value: (
                      <MeetingRequestStatusBadge
                        status={data.status}
                        label={statusLabel}
                        sx={{ borderRadius: "16px" }}
                      />
                    ),
                  },
                ]}
              />

              <MetaFieldsGrid
                fields={[
                  {
                    icon: <LineIcon type="user" />,
                    label: t.governmentAgency,
                    value: <AgencyInfo data={data} />,
                  },
                  {
                    icon: <LineIcon type="link" />,
                    label: t.meetingRequestDocument,
                    align: "start",
                    value: <MeetingRequestDocument path={data.meetingRequestLetter} />,
                  },
                ]}
              />
            </Box>

            <Box sx={{ display: "flex", flexDirection: "column", gap: "12px" }}>
              <Typography
                sx={{
                  color: isDark ? "#ffffff" : "#252b37",
                  fontSize: 16,
                  fontWeight: 700,
                  lineHeight: 1.2,
                }}
              >
                {t.description}
              </Typography>

              <Typography
                component="div"
                className={
                  isKhmerText(descriptionText) || uiLang === "km"
                    ? "font-kh"
                    : undefined
                }
                sx={{
                  p: "16px",
                  borderRadius: "12px",
                  bgcolor: isDark ? alpha("#ffffff", 0.04) : "#fafafa",
                  color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
                  fontSize: 13,
                  lineHeight: "22px",
                  whiteSpace: "pre-wrap",
                }}
              >
                {descriptionText}
              </Typography>
            </Box>

            <Box sx={{ display: "flex", flexDirection: "column", gap: "12px" }}>
              <Box sx={{ display: "flex", alignItems: "center", gap: "12px" }}>
                <Typography
                  sx={{
                    color: isDark ? "#ffffff" : "#252b37",
                    fontSize: 16,
                    fontWeight: 700,
                    lineHeight: 1.2,
                  }}
                >
                  {t.issueSubmitted}
                </Typography>

                <IssueCountBadge count={issues.length} />
              </Box>

              <Box sx={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                {issues.length === 0 ? (
                  <Box
                    sx={{
                      px: "22px",
                      py: "8px",
                      minHeight: 76,
                      borderRadius: "6px",
                      border: `1px solid ${isDark ? alpha("#ffffff", 0.08) : "#f5f5f5"}`,
                      bgcolor: isDark ? "#101828" : "#ffffff",
                      display: "flex",
                      alignItems: "center",
                    }}
                  >
                    <Typography sx={{ color: "#717680", fontSize: 13 }}>
                      No issue submitted
                    </Typography>
                  </Box>
                ) : null}

                {issues.map((issue) => (
                  <Box
                    key={issue.id}
                    sx={{
                      px: "22px",
                      py: "8px",
                      minHeight: 76,
                      borderRadius: "6px",
                      border: `1px solid ${isDark ? alpha("#ffffff", 0.08) : "#f5f5f5"}`,
                      bgcolor: isDark ? "#101828" : "#ffffff",
                      display: "flex",
                      alignItems: "center",
                    }}
                  >
                    <Box sx={{ minWidth: 0, width: "100%", py: "8px" }}>
                      <Typography
                        noWrap
                        className={
                          isKhmerText(issue.title) || uiLang === "km"
                            ? "font-kh"
                            : undefined
                        }
                        sx={{
                          color: isDark ? "#ffffff" : "#181d27",
                          fontSize: 13,
                          fontWeight: 500,
                          lineHeight: 1.2,
                        }}
                      >
                        {issue.title || "-"}
                      </Typography>

                      <Typography
                        noWrap
                        className={
                          isKhmerText(issue.description) || uiLang === "km"
                            ? "font-kh"
                            : undefined
                        }
                        sx={{
                          mt: "12px",
                          color: "#717680",
                          fontSize: 12,
                          fontWeight: 500,
                          lineHeight: 1.2,
                        }}
                      >
                        {stripHtml(issue.description) || "-"}
                      </Typography>
                    </Box>
                  </Box>
                ))}
              </Box>
            </Box>

          </Box>
        ) : null}
      </Box>
    </Dialog>
  );
}
