"use client";

import type { ReactNode } from "react";

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

import { AppDivider } from "@/components/ui/divider";
import { DocumentLink } from "@/components/ui/document-link";
import { DocumentFileAttachment } from "@/components/ui/document-file-name";
import {
  AccountCircleIcon,
  CategoryOfIssuesIcon,
  GovernmentAgencyIcon,
  HyperlinkIcon,
  SubmitDateIcon,
  WarningIcon,
} from "@/components/ui/icon";
import {
  IssueListAgencyCell,
  IssueListStatusCell,
} from "@/features/ministry/meeting-summary/components/view-meeting-summary/issue-list-table-cells";
import type { ViewMeetingSummaryIssueRow } from "@/features/ministry/meeting-summary/components/view-meeting-summary/view-meeting-summary-data";
import { isDocumentPlaceholder } from "@/lib/document-file";

const DIALOG_Z_INDEX = 1300;
const DETAIL_LABEL_WIDTH = 152;

type Props = {
  open: boolean;
  issue: ViewMeetingSummaryIssueRow | null;
  submittedBy?: string;
  submittedDate?: string;
  issueDocument?: string;
  issueDocumentSize?: string;
  onClose: () => void;
};

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

function DetailInfo({
  icon,
  label,
  value,
}: {
  icon: ReactNode;
  label: string;
  value: ReactNode;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        minWidth: 0,
        display: "flex",
        alignItems: "center",
        gap: 0.75,
      }}
    >
      <Box
        sx={{
          flexShrink: 0,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          width: 20,
          color: isDark ? alpha("#ffffff", 0.55) : "#717680",
        }}
      >
        {icon}
      </Box>

      <Box
        sx={{
          flex: 1,
          minWidth: 0,
          display: "flex",
          alignItems: "center",
          gap: 0.75,
        }}
      >
        <Typography
          sx={{
            width: DETAIL_LABEL_WIDTH,
            flexShrink: 0,
            fontSize: 13,
            fontWeight: 400,
            color: isDark ? alpha("#ffffff", 0.55) : "#717680",
            whiteSpace: "nowrap",
            lineHeight: "22px",
          }}
        >
          {label} :
        </Typography>

        {typeof value === "string" ? (
          <Typography
            className={isKhmerText(value) ? "font-kh" : undefined}
            noWrap
            sx={{
              flex: 1,
              minWidth: 0,
              overflow: "hidden",
              textOverflow: "ellipsis",
              fontSize: 13,
              fontWeight: 500,
              color: isDark ? "#ffffff" : "#181d27",
              lineHeight: "22px",
              cursor: "default",
            }}
          >
            {value}
          </Typography>
        ) : (
          <Box sx={{ flex: 1, minWidth: 0 }}>{value}</Box>
        )}
      </Box>
    </Box>
  );
}

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

  return (
    <Box sx={{ py: 2.75 }}>
      <Typography
        sx={{
          mb: 2,
          fontSize: 16,
          fontWeight: 700,
          color: isDark ? "#ffffff" : "#181d27",
        }}
      >
        {title}
      </Typography>

      <Typography
        className={isKhmerText(content) ? "font-kh" : undefined}
        sx={{
          fontSize: 13,
          fontWeight: 400,
          color: isDark ? alpha("#ffffff", 0.88) : "#181d27",
          lineHeight: "22px",
          textAlign: "justify",
          whiteSpace: "pre-wrap",
        }}
      >
        {content}
      </Typography>
    </Box>
  );
}

function displayValue(value: string, fallback = "-") {
  if (!value || value === "Not Uploaded") return fallback;
  return value;
}

export function ViewMeetingSummaryIssueDetailDialog({
  open,
  issue,
  submittedBy = "-",
  submittedDate = "-",
  issueDocument = "-",
  issueDocumentSize = "—",
  onClose,
}: Props) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  if (!issue) return null;

  const showResolutionSection =
    !isDocumentPlaceholder(issue.rgcDecision) ||
    !isDocumentPlaceholder(issue.nextStep) ||
    !isDocumentPlaceholder(issue.remark);

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth={false}
      sx={{ zIndex: DIALOG_Z_INDEX }}
      slotProps={{
        backdrop: {
          sx: {
            backgroundColor: "rgba(0, 0, 0, 0.45)",
            backdropFilter: "none",
          },
        },
        paper: {
          sx: {
            width: { xs: "calc(100vw - 32px)", md: 795 },
            maxWidth: "calc(100vw - 32px)",
            height: { xs: "auto", md: 708 },
            maxHeight: { xs: "calc(100vh - 32px)", md: 708 },
            borderRadius: "12px",
            bgcolor: isDark ? "#101828" : "#ffffff",
            backgroundImage: "none",
            color: isDark ? "#ffffff" : "#181d27",
            overflow: "hidden",
          },
        },
      }}
    >
      <Box
        sx={{
          height: 70,
          px: 3,
          display: "flex",
          alignItems: "center",
        }}
      >
        <Typography
          sx={{
            fontSize: 20,
            fontWeight: 500,
            color: isDark ? "#ffffff" : "#181d27",
            letterSpacing: "-0.4px",
          }}
        >
          Issues Detail
        </Typography>
      </Box>

      <AppDivider />

      <DialogContent
        sx={{
          px: 3,
          py: 3,
          bgcolor: isDark ? "#101828" : "#ffffff",
          overflowY: "auto",
        }}
      >
        <Typography
          className={isKhmerText(issue.issue) ? "font-kh" : undefined}
          sx={{
            pb: 2.75,
            fontSize: { xs: 20, md: 24 },
            fontWeight: 600,
            color: isDark ? "#ffffff" : "#181d27",
            lineHeight: 1.25,
          }}
        >
          {issue.issue}
        </Typography>

        <AppDivider sx={{ mx: -3 }} />

        <Box sx={{ py: 2.75 }}>
          <Typography
            sx={{
              mb: 2,
              fontSize: 16,
              fontWeight: 700,
              color: isDark ? "#ffffff" : "#181d27",
            }}
          >
            Submit Details
          </Typography>

          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
              columnGap: 7,
              rowGap: 2,
            }}
          >
            <DetailInfo
              icon={<AccountCircleIcon />}
              label="Submitted by"
              value={submittedBy}
            />

            <DetailInfo
              icon={<SubmitDateIcon />}
              label="Submitted Date"
              value={submittedDate}
            />

            <DetailInfo
              icon={<HyperlinkIcon />}
              label="Issue Document"
              value={
                isDocumentPlaceholder(issueDocument) || !issueDocument ? (
                  "-"
                ) : (
                  <DocumentLink
                    file={{ path: issueDocument }}
                    sx={{
                      display: "inline-flex",
                      alignItems: "center",
                      minWidth: 0,
                    }}
                  >
                    <DocumentFileAttachment
                      value={issueDocument}
                      fileSize={issueDocumentSize}
                      emptyLabel="-"
                    />
                  </DocumentLink>
                )
              }
            />

            <DetailInfo
              icon={<CategoryOfIssuesIcon />}
              label="Category of Issues"
              value={issue.category}
            />

            <DetailInfo
              icon={<GovernmentAgencyIcon />}
              label="Government Agency"
              value={
                <IssueListAgencyCell
                  name={issue.primaryAgency}
                  logo={issue.primaryAgencyLogo}
                />
              }
            />

            <DetailInfo
              icon={<WarningIcon />}
              label="Status"
              value={<IssueListStatusCell label={issue.status} />}
            />

            <DetailInfo
              icon={<GovernmentAgencyIcon />}
              label="Gov't Second Agency"
              value={displayValue(issue.secondAgency)}
            />

            <DetailInfo
              icon={<GovernmentAgencyIcon />}
              label="Gov't Third Agency"
              value={displayValue(issue.thirdAgency)}
            />

            <DetailInfo
              icon={<GovernmentAgencyIcon />}
              label="Gov't Fourth Agency"
              value={displayValue(issue.fourthAgency)}
            />

            <DetailInfo
              icon={<GovernmentAgencyIcon />}
              label="Gov't Fifth Agency"
              value={displayValue(issue.fifthAgency)}
            />

            <DetailInfo
              icon={<WarningIcon />}
              label="Issue Escalation"
              value={displayValue(issue.issueEscalation)}
            />

            <DetailInfo
              icon={<HyperlinkIcon />}
              label="Issue Reference"
              value={
                isDocumentPlaceholder(issue.issueReference) ||
                !issue.issueReference ? (
                  "-"
                ) : (
                  <DocumentLink
                    file={{ path: issue.issueReference }}
                    sx={{
                      display: "inline-flex",
                      alignItems: "center",
                      minWidth: 0,
                    }}
                  >
                    <DocumentFileAttachment
                      value={issue.issueReference}
                      emptyLabel="-"
                    />
                  </DocumentLink>
                )
              }
            />
          </Box>
        </Box>

        <AppDivider sx={{ mx: -3 }} />

        <DetailTextSection
          title="Issue Descriptions"
          content={issue.issueDescription}
        />

        <AppDivider sx={{ mx: -3 }} />

        <DetailTextSection
          title="Recommendations"
          content={issue.recommendation}
        />

        {showResolutionSection ? (
          <>
            <AppDivider sx={{ mx: -3 }} />

            {!isDocumentPlaceholder(issue.rgcDecision) ? (
              <DetailTextSection
                title="RGC Decision"
                content={issue.rgcDecision}
              />
            ) : null}

            {!isDocumentPlaceholder(issue.nextStep) ? (
              <>
                <AppDivider sx={{ mx: -3 }} />
                <DetailTextSection title="Next Step" content={issue.nextStep} />
              </>
            ) : null}

            {!isDocumentPlaceholder(issue.remark) ? (
              <>
                <AppDivider sx={{ mx: -3 }} />
                <DetailTextSection title="Remark" content={issue.remark} />
              </>
            ) : null}
          </>
        ) : null}
      </DialogContent>
    </Dialog>
  );
}
