"use client";

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

import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
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 { MeetingRequestStatusBadge } from "@/components/ui/meeting-request-status-badge";
import { AppDivider } from "@/components/ui/divider";
import { DocumentLink } from "@/components/ui/document-link";
import { DocumentFileAttachment } from "@/components/ui/document-file-name";
import { isDocumentPlaceholder } from "@/lib/document-file";
import {
  cdcGpsfMeetingRequestI18n,
  getCdcGpsfMeetingRequestFont,
} from "@/features/cdc-gpsf/meeting-requests/cdc-gpsf-meeting-request-i18n";
import { useCdcGpsfMeetingRequestI18n } from "@/features/cdc-gpsf/meeting-requests/use-cdc-gpsf-meeting-request-i18n";
import {
  cdcGpsfMeetingRequestService,
  resolveAssetUrl,
  type ApiIssue,
  type ApiMeetingRequest,
  type MeetingRequestStatus,
} from "@/features/cdc-gpsf/meeting-requests/service/cdc-gpsf-meeting-request-service";

import { CdcGpsfMeetingRequestIssueDetailDialog } from "./cdc-gpsf-meeting-request-issue-detail-dialog";

type CdcGpsfMeetingRequestDetailDialogProps = {
  open: boolean;
  meetingRequestId: number | null;
  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);
}

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 CdcGpsfMeetingRequestDetailDialog({
  open,
  meetingRequestId,
  onClose,
}: CdcGpsfMeetingRequestDetailDialogProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const uiLang = useCdcGpsfMeetingRequestI18n();
  const t = cdcGpsfMeetingRequestI18n(uiLang);
  const fontFamily = getCdcGpsfMeetingRequestFont(uiLang);

  const [data, setData] = useState<ApiMeetingRequest | null>(null);
  const [selectedIssue, setSelectedIssue] = useState<ApiIssue | 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);
        setSelectedIssue(null);

        const result =
          await cdcGpsfMeetingRequestService.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 && !selectedIssue}
      onClose={onClose}
      maxWidth={false}
      scroll="paper"
      sx={{
        "& .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
          sx={{
            fontSize: 20,
            fontWeight: 500,
            letterSpacing: "-0.4px",
            color: isDark ? "#f9fafb" : "#181d27",
          }}
        >
          {t.meetingRequestDetail}
        </Typography>

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

      <AppDivider />

      <Box
        sx={{
          px: 2.75,
          py: 2.75,
          overflowY: "auto",
          maxHeight: "calc(100dvh - 120px)",
        }}
      >
        {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" }}>
            <Typography
              className={
                isKhmerText(data?.title) || uiLang === "km" ? "font-kh" : undefined
              }
              sx={{
                fontSize: 20,
                fontWeight: 600,
                lineHeight: 1.25,
                color: isDark ? "#f9fafb" : "#181d27",
              }}
            >
              {data?.title || t.meetingRequestDetail}
            </Typography>

            <AppDivider />

            <Typography
              sx={{
                fontSize: 16,
                fontWeight: 700,
                color: isDark ? "#f9fafb" : "#414651",
              }}
            >
              {t.submitDetails}
            </Typography>

            <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.meetingRequest,
                    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) => (
                  <ButtonBase
                    key={issue.id}
                    onClick={() => setSelectedIssue(issue)}
                    sx={{
                      width: "100%",
                      display: "block",
                      textAlign: "left",
                      borderRadius: "6px",
                    }}
                  >
                    <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",
                        transition: "background-color 0.15s ease",
                        "&:hover": {
                          bgcolor: isDark ? alpha("#ffffff", 0.06) : "#fafafa",
                        },
                      }}
                    >
                      <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>
                  </ButtonBase>
                ))}
              </Box>
            </Box>
          </Box>
        ) : null}
      </Box>
    </Dialog>

    <CdcGpsfMeetingRequestIssueDetailDialog
      open={Boolean(selectedIssue)}
      issue={selectedIssue}
      meetingRequest={data}
      language={uiLang}
      onClose={() => setSelectedIssue(null)}
    />
  </>
  );
}
