"use client";

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

import { MeetingDetailIssuesTable } from "./meeting-detail-issues-table";
import { useAppLanguage } from "@/components/providers/app-language-provider";
import { AppDivider } from "@/components/ui/divider";
import { DocumentLink } from "@/components/ui/document-link";
import { DocumentFileAttachment } from "@/components/ui/document-file-name";
import {
  AccountCircleIcon,
  CategoryOfIssuesIcon,
  EmailIcon,
  GovernmentAgencyIcon,
  HyperlinkIcon,
  SubmitDateIcon,
  WarningIcon,
} from "@/components/ui/icon";
import { IssueStatusBadge } from "@/components/ui/issue-status-badge";
import { MeetingRequestStatusBadge } from "@/components/ui/meeting-request-status-badge";
import {
  isDocumentPlaceholder,
  type UploadedFileMetadata,
} from "@/lib/document-file";
import {
  formatCalendarDate,
  formatCalendarTimeText,
  type CalendarLanguage,
} from "@/components/ui/month-calendar";
import {
  i18n,
  type MeetingCalendarLabels,
} from "@/features/ministry/meeting-request/meeting-request-i18n";
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 { useTheme } from "@mui/material/styles";

type DetailStakeholder = {
  name?: string | null;
  logo?: string | null;
};

type DetailGovernmentAgency = {
  agencyOrder?: number | null;
  stakeholder?: DetailStakeholder | null;
  name?: string | null;
  logo?: string | null;
};

export type DetailIssue = {
  id?: number | string;
  title?: string | null;
  issue?: string | null;
  description?: string | null;
  recommendation?: string | null;
  status?: string | null;
  primaryAgency?: string | null;
  primaryAgencyLogo?: string | null;
  secondAgency?: string | null;
  thirdAgency?: string | null;
  fourthAgency?: string | null;
  fifthAgency?: string | null;
  secondAgencyLogo?: string | null;
  thirdAgencyLogo?: string | null;
  fourthAgencyLogo?: string | null;
  fifthAgencyLogo?: string | null;
  attachment?: string | null;
  createdAt?: string | null;
  governmentAgencies?: DetailGovernmentAgency[] | null;
  category?: { name?: string | null } | string | null;
  issueStatus?: { name?: string | null } | null;
};

type DetailMeetingRequest = {
  id?: number | null;
  title?: string | null;
  description?: string | null;
  meetingRequestLetter?: string | null;
  status?: string | null;
  submittedBy?: string | null;
  requestedBy?: string | null;
  requestedDate?: string | null;
  privateSectorWG?: string | null;
  user?: { name?: string | null; position?: string | null } | null;
  issues?: DetailIssue[] | null;
  governmentAgencies?: DetailGovernmentAgency[] | null;
};

export type DetailMeeting = {
  id: number;
  workingGroupName?: string | null;
  title?: string | null;
  description?: string | null;
  meetingDate?: string | null;
  startTime?: string | null;
  endTime?: string | null;
  location?: string | null;
  documentReference?: UploadedFileMetadata | null;
  status?: string | null;
  createdAt?: string | null;
  user?: { name?: string | null; position?: string | null } | null;
  meetingRequest?: DetailMeetingRequest | null;
};

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

  return (
    value
      .replace(/<[^>]*>/g, " ")
      .replace(/&amp;/g, "&")
      .replace(/&nbsp;/g, " ")
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/\s+/g, " ")
      .trim() || "-"
  );
}

function getDocumentPath(
  value?: UploadedFileMetadata | string | null,
): string | null {
  if (!value) return null;
  return typeof value === "string" ? value : value.path;
}

function isKhmerText(value: string) {
  return /[\u1780-\u17FF]/.test(value);
}

const MEETING_DETAIL_SECTION_TITLE_SX = {
  fontSize: 16,
  fontWeight: 700,
  color: "#414651",
} as const;

function formatDetailDate(
  value: string | null | undefined,
  language: CalendarLanguage,
) {
  if (!value) return "-";

  const directDateKey = value.match(/^\d{4}-\d{2}-\d{2}/)?.[0];
  if (directDateKey) {
    return formatCalendarDate(directDateKey, language);
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";

  return formatCalendarDate(date.toISOString().slice(0, 10), language);
}

function getMeetingStatusLabel(status?: string | null) {
  if (status === "DRAFT" || status === "Drafted") {
    return "Draft";
  }

  if (status === "SCHEDULED") {
    return "Scheduled";
  }

  if (status === "SUBMITTED") {
    return "Submitted";
  }

  if (status === "COMPLETED") {
    return "Completed";
  }

  return status || "Submitted";
}

function formatDetailTime(
  value: string | null | undefined,
  language: CalendarLanguage,
) {
  if (!value) return "-";

  const directTime = /^(\d{1,2}):(\d{2})/.exec(value);
  if (directTime) {
    const hour = Number(directTime[1]);
    const minute = Number(directTime[2]);

    if (hour <= 23 && minute <= 59) {
      const dayPeriod = hour >= 12 ? "PM" : "AM";
      const twelveHour = hour % 12 || 12;

      return formatCalendarTimeText(
        `${twelveHour}:${String(minute).padStart(2, "0")} ${dayPeriod}`,
        language,
      );
    }
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";

  const englishTime = new Intl.DateTimeFormat("en-US", {
    hour: "numeric",
    minute: "2-digit",
    hour12: true,
    timeZone: "UTC",
  }).format(date);

  return formatCalendarTimeText(englishTime, language);
}

function getApiOrigin() {
  const raw =
    process.env.NEXT_PUBLIC_API_URL ??
    process.env.NEXT_PUBLIC_API_BASE_URL ??
    "http://localhost:3001/api/v1";

  return raw.replace(/\/api\/v\d+\/?$/, "").replace(/\/+$/, "");
}

function getMediaUrl(path?: string | null) {
  if (!path) return "";
  if (/^https?:\/\//i.test(path)) return path;
  return `${getApiOrigin()}${path.startsWith("/") ? path : `/${path}`}`;
}

function firstAgencyName(agencies?: DetailGovernmentAgency[] | null) {
  const firstAgency = agencies?.[0];
  return firstAgency?.stakeholder?.name || firstAgency?.name || "-";
}

function firstAgencyLogo(agencies?: DetailGovernmentAgency[] | null) {
  const firstAgency = agencies?.[0];
  return firstAgency?.stakeholder?.logo || firstAgency?.logo || "";
}

const SUBMIT_DETAIL_LABEL_WIDTH = 152;

function InfoItem({
  icon,
  label,
  children,
  alignItems = "center",
  labelWidth = SUBMIT_DETAIL_LABEL_WIDTH,
}: {
  icon: ReactNode;
  label: string;
  children: ReactNode;
  alignItems?: "center" | "flex-start";
  labelWidth?: number;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        display: "flex",
        alignItems,
        gap: 0.75,
        minWidth: 0,
        width: "100%",
      }}
    >
      <Box
        sx={{
          color: isDark ? "#98a2b3" : "#717680",
          display: "flex",
          flexShrink: 0,
          width: 20,
          height: 20,
          alignItems: "center",
          justifyContent: "center",
          mt: alignItems === "flex-start" ? "1px" : 0,
        }}
      >
        {icon}
      </Box>
      <Typography
        sx={{
          width: labelWidth,
          flexShrink: 0,
          color: isDark ? "#d0d5dd" : "#717680",
          fontSize: 13,
          fontWeight: 400,
          lineHeight: "22px",
          whiteSpace: "nowrap",
        }}
      >
        {label} :
      </Typography>
      <Box
        sx={{
          flex: 1,
          minWidth: 0,
          color: isDark ? "#f9fafb" : "#181d27",
          fontSize: 13,
          fontWeight: 500,
          display: "flex",
          alignItems: "center",
        }}
      >
        {children}
      </Box>
    </Box>
  );
}

function DetailDocument({
  file,
  sizeLabel,
}: {
  file?: string | null;
  sizeLabel?: string;
}) {
  if (isDocumentPlaceholder(file) || !file) {
    return (
      <Typography sx={{ fontSize: 12, fontWeight: 500, color: "#252b37" }}>
        -
      </Typography>
    );
  }

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

function AgencyValue({
  name,
  logo,
  emptyLabel = "No data",
}: {
  name?: string | null;
  logo?: string | null;
  emptyLabel?: string;
}) {
  const mediaLogo = getMediaUrl(logo);
  const value = name?.trim() || emptyLabel;

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

function IssueAgencyValue({
  name,
  logo,
  emptyLabel = "No data",
}: {
  name?: string | null;
  logo?: string | null;
  emptyLabel?: string;
}) {
  const value = name?.trim();
  const isEmpty = !value || value === "No data";

  if (isEmpty) {
    return (
      <Typography sx={{ fontSize: 12, fontWeight: 500, color: "#717680" }}>
        {emptyLabel}
      </Typography>
    );
  }

  return <AgencyValue name={value} logo={logo} />;
}

function IssueDetailTextSection({
  title,
  content,
}: {
  title: string;
  content: string;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const sectionTitleSx = {
    ...MEETING_DETAIL_SECTION_TITLE_SX,
    color: isDark ? "#f9fafb" : MEETING_DETAIL_SECTION_TITLE_SX.color,
  };

  return (
    <Box>
      <Typography sx={{ ...sectionTitleSx, mb: 2 }}>{title}</Typography>
      <Typography
        className={isKhmerText(content) ? "font-kh" : undefined}
        sx={{
          fontSize: 13,
          fontWeight: 500,
          lineHeight: 1.7,
          textAlign: "justify",
          whiteSpace: "pre-wrap",
          color: isDark ? "#e5e7eb" : "#181d27",
        }}
      >
        {content}
      </Typography>
    </Box>
  );
}

function getIssueAgency(
  issue: DetailIssue,
  order: number,
  primaryFallback?: DetailGovernmentAgency,
) {
  const byOrder = issue.governmentAgencies?.find(
    (agency) => agency.agencyOrder === order,
  );

  const agencyNameKey = [
    "",
    "primaryAgency",
    "secondAgency",
    "thirdAgency",
    "fourthAgency",
    "fifthAgency",
  ][order] as keyof DetailIssue;
  const agencyLogoKey = [
    "",
    "primaryAgencyLogo",
    "secondAgencyLogo",
    "thirdAgencyLogo",
    "fourthAgencyLogo",
    "fifthAgencyLogo",
  ][order] as keyof DetailIssue;

  return {
    name:
      byOrder?.stakeholder?.name ||
      byOrder?.name ||
      (issue[agencyNameKey] as string | null | undefined) ||
      (order === 1
        ? primaryFallback?.stakeholder?.name || primaryFallback?.name
        : undefined) ||
      "No data",
    logo:
      byOrder?.stakeholder?.logo ||
      byOrder?.logo ||
      (issue[agencyLogoKey] as string | null | undefined) ||
      (order === 1
        ? primaryFallback?.stakeholder?.logo || primaryFallback?.logo
        : undefined) ||
      "",
  };
}

export function MeetingCalendarIssueDetailDialog({
  open,
  issue,
  meeting,
  onClose,
  labels,
  statusLabels,
}: {
  open: boolean;
  issue: DetailIssue | null;
  meeting: DetailMeeting | null;
  onClose: () => void;
  labels: MeetingCalendarLabels;
  statusLabels: Readonly<Record<string, string>>;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const { language } = useAppLanguage();
  const request = meeting?.meetingRequest;
  const primaryAgencyFallback = request?.governmentAgencies?.[0];
  const primaryAgency = issue
    ? getIssueAgency(issue, 1, primaryAgencyFallback)
    : { name: "No data", logo: "" };
  const secondAgency = issue
    ? getIssueAgency(issue, 2)
    : { name: "No data", logo: "" };
  const thirdAgency = issue
    ? getIssueAgency(issue, 3)
    : { name: "No data", logo: "" };
  const fourthAgency = issue
    ? getIssueAgency(issue, 4)
    : { name: "No data", logo: "" };
  const fifthAgency = issue
    ? getIssueAgency(issue, 5)
    : { name: "No data", logo: "" };
  const documentFile =
    issue?.attachment ||
    getDocumentPath(meeting?.documentReference) ||
    request?.meetingRequestLetter;
  const issueTitle = stripHtmlText(issue?.title || issue?.issue);
  const issueDescription = stripHtmlText(issue?.description);
  const issueRecommendation = stripHtmlText(issue?.recommendation);
  const issueStatus = issue?.status || issue?.issueStatus?.name || "Not Addressed";
  const issueStatusLabel = statusLabels[issueStatus] ?? issueStatus;
  const sectionTitleSx = {
    ...MEETING_DETAIL_SECTION_TITLE_SX,
    color: isDark ? "#f9fafb" : MEETING_DETAIL_SECTION_TITLE_SX.color,
  };
  const submittedBy =
    meeting?.workingGroupName?.trim() ||
    request?.privateSectorWG ||
    request?.user?.position ||
    request?.user?.name ||
    request?.submittedBy ||
    "-";

  if (!issue) return null;

  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",
            bgcolor: isDark ? "#101828" : "#ffffff",
            backgroundImage: "none",
            overflow: "hidden",
          },
        },
      }}
    >
      <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",
          }}
        >
          {labels.detail.issueDetail}
        </Typography>
        <IconButton
          onClick={onClose}
          size="small"
          aria-label={labels.detail.close}
          sx={{ color: isDark ? "#d0d5dd" : "#717680" }}
        >
          ✕
        </IconButton>
      </Box>

      <AppDivider />

      <Box
        sx={{
          px: 2.75,
          py: 2.75,
          overflowY: "auto",
          maxHeight: "calc(100dvh - 120px)",
        }}
      >
        <Typography
          className={isKhmerText(issueTitle) ? "font-kh" : undefined}
          sx={{
            fontSize: 24,
            fontWeight: 600,
            lineHeight: 1.25,
            color: isDark ? "#f9fafb" : "#181d27",
          }}
        >
          {issueTitle}
        </Typography>

        <Typography sx={{ ...sectionTitleSx, mt: 2.75, mb: 2 }}>
          {labels.detail.submitDetails}
        </Typography>

        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
            columnGap: { xs: 2, md: 4 },
            rowGap: 2,
            alignItems: "center",
          }}
        >
          <InfoItem
            icon={<AccountCircleIcon sx={{ fontSize: 20 }} />}
            label={labels.detail.submittedBy}
          >
            <Typography noWrap sx={{ fontSize: 13, fontWeight: 500 }}>
              {submittedBy}
            </Typography>
          </InfoItem>

          <InfoItem
            icon={<SubmitDateIcon sx={{ fontSize: 20 }} />}
            label={labels.detail.submittedDate}
          >
            <Typography sx={{ fontSize: 13, fontWeight: 500 }}>
              {formatDetailDate(
                issue.createdAt ||
                  request?.requestedDate ||
                  meeting?.createdAt ||
                  meeting?.meetingDate,
                language,
              )}
            </Typography>
          </InfoItem>

          <InfoItem
            icon={<HyperlinkIcon sx={{ fontSize: 20 }} />}
            label={labels.detail.issueDocument}
            alignItems="flex-start"
          >
            <DetailDocument file={documentFile} />
          </InfoItem>

          <InfoItem
            icon={<CategoryOfIssuesIcon sx={{ fontSize: 20 }} />}
            label={labels.detail.categoryOfIssues}
          >
            <Typography noWrap sx={{ fontSize: 13, fontWeight: 500 }}>
              {(typeof issue.category === "string"
                ? issue.category
                : issue.category?.name) || "-"}
            </Typography>
          </InfoItem>

          <InfoItem
            icon={<GovernmentAgencyIcon sx={{ fontSize: 20 }} />}
            label={labels.detail.governmentAgency}
          >
            <IssueAgencyValue
              name={primaryAgency.name}
              logo={primaryAgency.logo}
              emptyLabel={labels.detail.noData}
            />
          </InfoItem>

          <InfoItem
            icon={<WarningIcon sx={{ fontSize: 18 }} />}
            label={labels.detail.status}
          >
            <IssueStatusBadge status={issueStatus} label={issueStatusLabel} />
          </InfoItem>

          <InfoItem
            icon={<GovernmentAgencyIcon sx={{ fontSize: 20 }} />}
            label={labels.issueTable.govtSecondAgency}
          >
            <IssueAgencyValue
              name={secondAgency.name}
              logo={secondAgency.logo}
              emptyLabel={labels.detail.noData}
            />
          </InfoItem>

          <InfoItem
            icon={<GovernmentAgencyIcon sx={{ fontSize: 20 }} />}
            label={labels.issueTable.govtThirdAgency}
          >
            <IssueAgencyValue
              name={thirdAgency.name}
              logo={thirdAgency.logo}
              emptyLabel={labels.detail.noData}
            />
          </InfoItem>

          <InfoItem
            icon={<GovernmentAgencyIcon sx={{ fontSize: 20 }} />}
            label={labels.issueTable.govtFourthAgency}
          >
            <IssueAgencyValue
              name={fourthAgency.name}
              logo={fourthAgency.logo}
              emptyLabel={labels.detail.noData}
            />
          </InfoItem>

          <InfoItem
            icon={<GovernmentAgencyIcon sx={{ fontSize: 20 }} />}
            label={labels.issueTable.govtFifthAgency}
          >
            <IssueAgencyValue
              name={fifthAgency.name}
              logo={fifthAgency.logo}
              emptyLabel={labels.detail.noData}
            />
          </InfoItem>
        </Box>

        <AppDivider sx={{ my: 2.75 }} />

        <IssueDetailTextSection
          title={labels.detail.issueDescriptions}
          content={issueDescription}
        />

        <AppDivider sx={{ my: 2.75 }} />

        <IssueDetailTextSection
          title={labels.detail.recommendations}
          content={issueRecommendation}
        />
      </Box>
    </Dialog>
  );
}

export function MeetingDetailDialog({
  open,
  meeting,
  onClose,
  labels = i18n.en.meetingCalendar,
  statusLabels = i18n.en.statusLabels,
}: {
  open: boolean;
  meeting: DetailMeeting | null;
  onClose: () => void;
  labels?: MeetingCalendarLabels;
  statusLabels?: Readonly<Record<string, string>>;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const { language } = useAppLanguage();
  const request = meeting?.meetingRequest;
  const issues = request?.issues ?? [];
  const agencies = request?.governmentAgencies ?? [];
  const documentFile =
    getDocumentPath(meeting?.documentReference) ||
    request?.meetingRequestLetter;
  const [selectedIssue, setSelectedIssue] = useState<DetailIssue | null>(null);
  const meetingDetailTitle = stripHtmlText(
    request?.title || meeting?.title || "-",
  );
  const meetingDescription = stripHtmlText(
    meeting?.description || request?.description,
  );
  const sectionTitleSx = {
    ...MEETING_DETAIL_SECTION_TITLE_SX,
    color: isDark ? "#f9fafb" : MEETING_DETAIL_SECTION_TITLE_SX.color,
  };
  const meetingStatus = getMeetingStatusLabel(
    meeting?.status || request?.status,
  );
  const meetingStatusLabel = statusLabels[meetingStatus] ?? meetingStatus;

  return (
    <>
      <Dialog
        open={open && !selectedIssue}
        onClose={onClose}
        maxWidth={false}
        scroll="paper"
        sx={{
          zIndex: 1600,
          "& .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",
              bgcolor: isDark ? "#101828" : "#ffffff",
              backgroundImage: "none",
              overflow: "hidden",
            },
          },
        }}
      >
        <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",
            }}
          >
            {labels.detail.meetingDetail}
          </Typography>
          <IconButton
            onClick={onClose}
            size="small"
            aria-label={labels.detail.close}
            sx={{ color: isDark ? "#d0d5dd" : "#717680" }}
          >
            ✕
          </IconButton>
        </Box>

        <AppDivider />

        <Box
          sx={{
            px: 2.75,
            py: 2.75,
            overflowY: "auto",
            maxHeight: "calc(100dvh - 120px)",
          }}
        >
          <Typography
            className={isKhmerText(meetingDetailTitle) ? "font-kh" : undefined}
            sx={{
              fontSize: 20,
              fontWeight: 600,
              lineHeight: 1.25,
              color: isDark ? "#f9fafb" : "#181d27",
            }}
          >
            {meetingDetailTitle}
          </Typography>

          <AppDivider sx={{ my: 2.75 }} />

          <Typography sx={{ ...sectionTitleSx, mb: 2 }}>
            {labels.detail.submitDetails}
          </Typography>

          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: {
                xs: "1fr",
                md: "minmax(0, 1fr) minmax(0, 1fr)",
              },
              columnGap: { xs: 2, md: 4 },
              rowGap: 2,
              alignItems: "center",
            }}
          >
            <InfoItem
              icon={<AccountCircleIcon sx={{ fontSize: 20 }} />}
              label={labels.detail.wgMeeting}
            >
              <Typography noWrap sx={{ fontSize: 13, fontWeight: 500 }}>
                {meeting?.workingGroupName?.trim() ||
                  request?.privateSectorWG ||
                  request?.user?.position ||
                  request?.user?.name ||
                  "-"}
              </Typography>
            </InfoItem>

            <InfoItem
              icon={<SubmitDateIcon sx={{ fontSize: 20 }} />}
              label={labels.detail.submittedDate}
            >
              <Typography sx={{ fontSize: 13, fontWeight: 500 }}>
                {formatDetailDate(
                  request?.requestedDate ||
                    meeting?.createdAt ||
                    meeting?.meetingDate,
                  language,
                )}
              </Typography>
            </InfoItem>

            <InfoItem
              icon={<HyperlinkIcon sx={{ fontSize: 20 }} />}
              label={labels.detail.meetingReference}
              alignItems="flex-start"
            >
              <DetailDocument file={documentFile} />
            </InfoItem>

            <InfoItem
              icon={<GovernmentAgencyIcon sx={{ fontSize: 20 }} />}
              label={labels.detail.governmentAgency}
            >
              <AgencyValue
                name={firstAgencyName(agencies)}
                logo={firstAgencyLogo(agencies)}
                emptyLabel={labels.detail.noData}
              />
            </InfoItem>

            <InfoItem
              icon={<WarningIcon sx={{ fontSize: 18 }} />}
              label={labels.detail.status}
            >
              <MeetingRequestStatusBadge
                status={meetingStatus}
                label={meetingStatusLabel}
              />
            </InfoItem>

            <InfoItem icon={<EmailIcon sx={{ fontSize: 20 }} />} label={labels.detail.sentBy}>
              <Typography sx={{ fontSize: 12, fontWeight: 500 }}>
                {meeting?.user?.name ||
                  meeting?.user?.position ||
                  request?.submittedBy ||
                  request?.requestedBy ||
                  "-"}
              </Typography>
            </InfoItem>
          </Box>

          <AppDivider sx={{ my: 2.75 }} />

          <Typography sx={{ ...sectionTitleSx, mb: 2 }}>
            {labels.detail.meetingInformation}
          </Typography>
          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: "auto 1fr",
              columnGap: 1,
              rowGap: 0.5,
              alignItems: "start",
            }}
          >
            <Typography sx={{ fontSize: 13, lineHeight: "22px", color: isDark ? "#e5e7eb" : "#181d27" }}>
              {labels.detail.date}:
            </Typography>
            <Typography sx={{ fontSize: 13, lineHeight: "22px", fontWeight: 500, color: isDark ? "#e5e7eb" : "#181d27" }}>
              {formatDetailDate(meeting?.meetingDate, language)}
            </Typography>
            <Typography sx={{ fontSize: 13, lineHeight: "22px", color: isDark ? "#e5e7eb" : "#181d27" }}>
              {labels.detail.time}:
            </Typography>
            <Typography sx={{ fontSize: 13, lineHeight: "22px", fontWeight: 500, color: isDark ? "#e5e7eb" : "#181d27" }}>
              {formatDetailTime(meeting?.startTime, language)} -{" "}
              {formatDetailTime(meeting?.endTime, language)}
            </Typography>
            <Typography sx={{ fontSize: 13, lineHeight: "22px", color: isDark ? "#e5e7eb" : "#181d27" }}>
              {labels.detail.location}:
            </Typography>
            <Typography sx={{ fontSize: 13, lineHeight: "22px", fontWeight: 500, color: isDark ? "#e5e7eb" : "#181d27" }}>
              {meeting?.location || "-"}
            </Typography>
          </Box>

          <Typography sx={{ ...sectionTitleSx, mt: 2.75, mb: 2 }}>
            {labels.detail.descriptions}
          </Typography>
          <Typography
            className={isKhmerText(meetingDescription) ? "font-kh" : undefined}
            sx={{
              fontSize: 13,
              fontWeight: 500,
              lineHeight: 1.7,
              textAlign: "justify",
              whiteSpace: "pre-wrap",
              color: isDark ? "#e5e7eb" : "#181d27",
            }}
          >
            {meetingDescription}
          </Typography>

          <Typography sx={{ ...sectionTitleSx, mt: 2.75, mb: 2 }}>
            {labels.detail.listOfIssues}
          </Typography>

          <MeetingDetailIssuesTable
            issues={issues}
            isDark={isDark}
            onViewIssue={setSelectedIssue}
            stripHtmlText={stripHtmlText}
            getIssueAgency={getIssueAgency}
            getMediaUrl={getMediaUrl}
            labels={labels}
            statusLabels={statusLabels}
          />
        </Box>
      </Dialog>
      <MeetingCalendarIssueDetailDialog
        open={Boolean(selectedIssue)}
        issue={selectedIssue}
        meeting={meeting}
        onClose={() => setSelectedIssue(null)}
        labels={labels}
        statusLabels={statusLabels}
      />
    </>
  );
}
