"use client";

import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import {
  useParams,
  useRouter,
  useSearchParams,
} from "next/navigation";

import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import ChatBubbleOutlineRoundedIcon from "@mui/icons-material/ChatBubbleOutlineRounded";
import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import InsertDriveFileOutlinedIcon from "@mui/icons-material/InsertDriveFileOutlined";
import NoteAddOutlinedIcon from "@mui/icons-material/NoteAddOutlined";
import ScheduleOutlinedIcon from "@mui/icons-material/ScheduleOutlined";
import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import Paper from "@mui/material/Paper";
import Snackbar from "@mui/material/Snackbar";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { PdfDocumentIcon } from "@/components/ui/pdf-document-icon";

import { useMinistryPlenaryDetail } from "../components/hook/use-ministry-plenaries";
import {
  createMinistryRgcDecision,
  submitRgcDecisionNotificationToCdc,
} from "../components/service/ministry-plenary-service";
import {
  CreateRgcDecisionDialog,
  type RgcDecisionFormData,
} from "../components/plenary/create-rgc-decision-dialog";
import { PlenaryDetailTable } from "../components/plenary/plenary-detail-table";
import { PlenaryStatusChip } from "../components/plenary/plenary-status-chip";
import { getMinistryPlenaryText } from "../plenary-i18n";

type DetailItemProps = {
  icon: ReactNode;
  label: string;
  value: ReactNode;
};

type Feedback = {
  severity: "success" | "error";
  message: string;
};

type PlenaryDocumentFields = {
  documentUrl?: string | null;
  documentReference?: string | null;
};

type PlenaryAttachmentProps = {
  name: string;
  size: string;
  url: string;
};

function formatFileSize(bytes: number): string {
  if (!Number.isFinite(bytes) || bytes <= 0) {
    return "-";
  }

  if (bytes < 1024) {
    return `${Math.round(bytes)} B`;
  }

  const kilobytes = bytes / 1024;

  if (kilobytes < 1024) {
    return `${kilobytes.toFixed(
      kilobytes >= 100 ? 0 : 1,
    )} KB`;
  }

  const megabytes = kilobytes / 1024;

  return `${megabytes.toFixed(
    megabytes >= 100 ? 0 : 2,
  )} MB`;
}

function PlenaryAttachment({
  name,
  size,
  url,
}: PlenaryAttachmentProps) {
  const content = (
    <Stack
      direction="row"
      spacing={1}
      sx={{
        minWidth: 0,
        alignItems: "center",
      }}
    >
      <Box
        sx={{
          display: "inline-flex",
          flexShrink: 0,
        }}
      >
        <PdfDocumentIcon size={20} />
      </Box>

      <Box sx={{ minWidth: 0 }}>
        <Typography
          variant="body2"
          title={name}
          sx={{
            overflow: "hidden",
            color: "text.primary",
            fontWeight: 700,
            whiteSpace: "nowrap",
            textOverflow: "ellipsis",
          }}
        >
          {name}
        </Typography>

        <Typography variant="caption" color="text.secondary">
          {size || "-"}
        </Typography>
      </Box>
    </Stack>
  );

  if (!url) {
    return content;
  }

  return (
    <Box
      component="a"
      href={url}
      target="_blank"
      rel="noopener noreferrer"
      aria-label={`View ${name}`}
      title={`View ${name}`}
      sx={{
        display: "inline-block",
        maxWidth: "100%",
        color: "inherit",
        textDecoration: "none",
        cursor: "pointer",

        "&:hover .MuiTypography-root:first-of-type": {
          color: "primary.main",
          textDecoration: "underline",
        },

        "&:focus-visible": {
          borderRadius: 1,
          outline: "2px solid",
          outlineColor: "primary.main",
          outlineOffset: 3,
        },
      }}
    >
      {content}
    </Box>
  );
}

type DecisionLike = {
  id?: number | string;
  status?: string | null;
  statusCode?: string | null;
  statusPlenary?: string | null;
  workflowStatus?: string | null;
  submissionStatus?: string | null;
  isDraft?: boolean | null;
  saveAsDraft?: boolean | null;
  isSubmittedToCdc?: boolean | null;
  submittedToCdc?: boolean | null;
  sentToCdc?: boolean | null;
  submittedToCdcAt?: string | null;
};

function hasValidDecisionId(decision: DecisionLike): boolean {
  const id = Number(decision.id);

  return Number.isInteger(id) && id > 0;
}

function normalizeWorkflowValue(value: unknown): string {
  return String(value ?? "")
    .trim()
    .toUpperCase()
    .replace(/[\s-]+/g, "_");
}

function isDraftDecision(
  decision: DecisionLike,
  submittedDecisionIds: ReadonlySet<number>,
): boolean {
  if (!hasValidDecisionId(decision)) {
    return false;
  }

  const decisionId = Number(decision.id);

  // Immediately treat records submitted in this screen as submitted.
  if (submittedDecisionIds.has(decisionId)) {
    return false;
  }

  const submittedAt = String(decision.submittedToCdcAt ?? "").trim();

  if (
    submittedAt ||
    decision.isSubmittedToCdc === true ||
    decision.submittedToCdc === true ||
    decision.sentToCdc === true
  ) {
    return false;
  }

  const workflowValues = [
    decision.statusPlenary,
    decision.workflowStatus,
    decision.submissionStatus,
  ].map(normalizeWorkflowValue);

  if (
    workflowValues.some((value) =>
      ["SUBMIT", "SUBMITTED", "SENT"].includes(value),
    )
  ) {
    return false;
  }

  if (
    decision.isDraft === true ||
    decision.saveAsDraft === true ||
    decision.submittedToCdcAt === null ||
    workflowValues.some((value) =>
      ["DRAFT", "SAVE_DRAFT"].includes(value),
    )
  ) {
    return true;
  }

  // Older API mappings may omit workflow fields completely.
  // The table displays those records as Save Draft, so they must remain
  // submittable instead of showing a false "No Save Draft" error.
  return true;
}

function getErrorMessage(error: unknown, fallback: string): string {
  if (error instanceof Error && error.message.trim()) {
    return error.message;
  }

  return fallback;
}

function getFormCategoryId(formData: RgcDecisionFormData): number {
  const categoryId = Number(
    (formData as unknown as { categoryId?: number | string }).categoryId,
  );

  return Number.isInteger(categoryId) && categoryId > 0 ? categoryId : 0;
}

function getFormStatus(formData: RgcDecisionFormData): string {
  const status = String(
    (formData as unknown as { status?: string }).status || "",
  ).trim();

  return status || "In Progress";
}

function getFormDecision(formData: RgcDecisionFormData): string {
  return String(
    (formData as unknown as { decision?: string }).decision || "",
  ).trim();
}

function getFormVerificationSource(formData: RgcDecisionFormData): string {
  return String(
    (formData as unknown as { verificationSource?: string })
      .verificationSource || "",
  ).trim();
}

function getFormIndicatorId(formData: RgcDecisionFormData): number {
  const indicatorId = Number(
    (formData as unknown as { indicatorId?: number | string }).indicatorId,
  );

  return Number.isInteger(indicatorId) && indicatorId > 0 ? indicatorId : 0;
}

function getFormMeetingDate(formData: RgcDecisionFormData): string {
  return String(
    (formData as unknown as { meetingDate?: string }).meetingDate || "",
  ).trim();
}

function getFormFocalPerson(formData: RgcDecisionFormData): string {
  return String(
    (formData as unknown as { focalPerson?: string }).focalPerson || "",
  ).trim();
}

function getFormVerificationLink(formData: RgcDecisionFormData): string {
  return String(
    (formData as unknown as { verificationLink?: string }).verificationLink ||
      "",
  ).trim();
}

function DetailItem({ icon, label, value }: DetailItemProps) {
  const isSimpleValue =
    typeof value === "string" || typeof value === "number";

  return (
    <Stack
      direction="row"
      spacing={1.25}
      sx={{
        minWidth: 0,
        alignItems: "center",
      }}
    >
      <Box
        sx={{
          display: "inline-flex",
          flexShrink: 0,
          color: "text.secondary",
        }}
      >
        {icon}
      </Box>

      <Stack
        direction="row"
        spacing={1}
        sx={{
          minWidth: 0,
          alignItems: "center",
          flexWrap: "wrap",
        }}
      >
        <Typography
          variant="body2"
          sx={{
            color: "text.secondary",
            whiteSpace: "nowrap",
          }}
        >
          {label}
        </Typography>

        {isSimpleValue ? (
          <Typography
            variant="body2"
            sx={{
              minWidth: 0,
              color: "text.primary",
              fontWeight: 700,
            }}
          >
            {value}
          </Typography>
        ) : (
          value
        )}
      </Stack>
    </Stack>
  );
}

function SubmittingOverlay({ label = "Submitting" }: { label?: string }) {
  return (
    <Box
      role="status"
      aria-label={label}
      sx={{
        position: "fixed",
        inset: 0,
        zIndex: 2200,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        bgcolor: "rgba(255, 255, 255, 0.85)",
      }}
    >
      <Stack direction="row" spacing={1.25}>
        {[0, 1, 2, 3].map((dot) => (
          <Box
            key={dot}
            component="span"
            sx={{
              width: 10,
              height: 10,
              display: "block",
              borderRadius: "50%",
              bgcolor: "#2563EB",
              animation:
                "ministryPlenarySubmitPulse 0.9s ease-in-out infinite",
              animationDelay: `${dot * 0.15}s`,
              "@keyframes ministryPlenarySubmitPulse": {
                "0%, 100%": {
                  opacity: 0.35,
                  transform: "scale(0.85)",
                },
                "50%": {
                  opacity: 1,
                  transform: "scale(1)",
                },
              },
            }}
          />
        ))}
      </Stack>
    </Box>
  );
}

export function PlenaryDetailScreen() {
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();
  const theme = useTheme();
  const { language } = useAppLanguage();
  const text = getMinistryPlenaryText(language);

  const rawId = params?.id;
  const plenaryIdText = Array.isArray(rawId) ? rawId[0] : rawId;
  const plenaryId = Number(plenaryIdText);

  const {
    item: plenary,
    loading,
    error,
    refetch,
  } = useMinistryPlenaryDetail(plenaryId);

  const [submitDialogOpen, setSubmitDialogOpen] = useState(false);
  const [isSubmittingToCdc, setIsSubmittingToCdc] = useState(false);
  const [isRgcSubmitting, setIsRgcSubmitting] = useState(false);
  const [createRgcDecisionOpen, setCreateRgcDecisionOpen] =
    useState(false);
  const [submittedDecisionIds, setSubmittedDecisionIds] = useState<
    Set<number>
  >(() => new Set());

  const createRgcDecisionRequested =
    searchParams.get("createRgcDecision") === "1";
  const [feedback, setFeedback] = useState<Feedback | null>(null);

  const documentFields =
    plenary as unknown as PlenaryDocumentFields | null;

  const documentUrl = String(
    documentFields?.documentUrl ??
      documentFields?.documentReference ??
      "",
  ).trim();

  const mappedDocumentSize = String(
    plenary?.documentSize ?? "",
  ).trim();

  const [fetchedDocumentSize, setFetchedDocumentSize] =
    useState<{
      url: string;
      size: string;
    } | null>(null);

  const resolvedDocumentSize =
    mappedDocumentSize &&
    mappedDocumentSize !== "-"
      ? mappedDocumentSize
      : fetchedDocumentSize?.url === documentUrl
        ? fetchedDocumentSize.size
        : "-";

  useEffect(() => {
    if (
      !documentUrl ||
      (mappedDocumentSize &&
        mappedDocumentSize !== "-")
    ) {
      return;
    }

    const abortController =
      new AbortController();

    let active = true;

    async function loadDocumentSize() {
      try {
        const response = await fetch(documentUrl, {
          method: "HEAD",
          credentials: "include",
          cache: "no-store",
          signal: abortController.signal,
        });

        if (!response.ok) {
          throw new Error(
            `Unable to read PDF size (${response.status}).`,
          );
        }

        const contentLength = Number(
          response.headers.get("content-length"),
        );

        if (active) {
          setFetchedDocumentSize({
            url: documentUrl,
            size: formatFileSize(contentLength),
          });
        }
      } catch (error) {
        const requestWasAborted =
          error instanceof DOMException &&
          error.name === "AbortError";

        if (active && !requestWasAborted) {
          setFetchedDocumentSize({
            url: documentUrl,
            size: "-",
          });
        }
      }
    }

    void loadDocumentSize();

    return () => {
      active = false;
      abortController.abort();
    };
  }, [documentUrl, mappedDocumentSize]);

  const closeCreateRgcDecisionDialog = () => {
    setCreateRgcDecisionOpen(false);

    if (searchParams.get("createRgcDecision") === "1") {
      router.replace(`/ministry/plenary/plenaries/${plenaryId}`);
    }
  };

  async function handleSubmitToCdc() {
    if (!plenaryId || Number.isNaN(plenaryId) || !plenary) {
      return;
    }

    const draftDecisions = (plenary.rgcDecisions ?? []).filter(
      (decision) =>
        isDraftDecision(
          decision as DecisionLike,
          submittedDecisionIds,
        ),
    );

    if (draftDecisions.length === 0) {
      setSubmitDialogOpen(false);
      setFeedback({
        severity: "error",
        message: text.noDraftToSubmit,
      });
      return;
    }

    try {
      setSubmitDialogOpen(false);
      setIsSubmittingToCdc(true);

      const submittedIds = draftDecisions.map((decision) =>
        Number(decision.id),
      );

      await Promise.all(
        submittedIds.map((decisionId) =>
          submitRgcDecisionNotificationToCdc(decisionId),
        ),
      );

      // Update the Status Plenary chip immediately, even before refetch
      // finishes or when an older frontend mapper drops submittedToCdcAt.
      setSubmittedDecisionIds((current) => {
        const next = new Set(current);

        submittedIds.forEach((decisionId) => next.add(decisionId));

        return next;
      });

      window.dispatchEvent(new Event("system-notification-updated"));

      await refetch();

      setFeedback({
        severity: "success",
        message:
          text.submitSuccess,
      });
    } catch (submitError: unknown) {
      setFeedback({
        severity: "error",
        message: getErrorMessage(
          submitError,
          text.submitError,
        ),
      });
    } finally {
      setIsSubmittingToCdc(false);
    }
  }

  async function handleSaveRgcDraft(formData: RgcDecisionFormData) {
    if (isRgcSubmitting) {
      return;
    }

    try {
      setIsRgcSubmitting(true);

      if (!plenaryId || Number.isNaN(plenaryId)) {
        throw new Error(text.invalidPlenaryId);
      }

      const categoryId = getFormCategoryId(formData);
      const indicatorId = getFormIndicatorId(formData);
      const status = getFormStatus(formData);
      const meetingDate = getFormMeetingDate(formData);
      const focalPerson = getFormFocalPerson(formData);
      const decision = getFormDecision(formData);
      const verificationSource = getFormVerificationSource(formData);
      const verificationLink = getFormVerificationLink(formData);

      if (!categoryId) {
        throw new Error(text.selectCategoryError);
      }

      if (!indicatorId) {
        throw new Error(text.selectIndicatorError);
      }

      if (!meetingDate) {
        throw new Error(text.selectMeetingDateError);
      }

      if (!focalPerson) {
        throw new Error(text.enterFocalPersonError);
      }

      if (!decision) {
        throw new Error(text.enterDecisionError);
      }

      if (!verificationSource) {
        throw new Error(text.enterVerificationSourceError);
      }

      await createMinistryRgcDecision({
        plenaryId,
        categoryId,
        indicatorId,
        status,
        meetingDate,
        focalPerson,
        decision,
        verificationSource,
        verificationLink,
      });

      await refetch();

      closeCreateRgcDecisionDialog();

      setFeedback({
        severity: "success",
        message: text.saveDraftSuccess,
      });
    } catch (saveError: unknown) {
      setFeedback({
        severity: "error",
        message: getErrorMessage(
          saveError,
          text.saveDraftError,
        ),
      });
    } finally {
      setIsRgcSubmitting(false);
    }
  }

  async function handleSendRgcNotification(formData: RgcDecisionFormData) {
    if (isRgcSubmitting) {
      return;
    }

    try {
      setIsRgcSubmitting(true);

      if (!plenaryId || Number.isNaN(plenaryId)) {
        throw new Error(text.invalidPlenaryId);
      }

      const categoryId = getFormCategoryId(formData);
      const indicatorId = getFormIndicatorId(formData);
      const status = getFormStatus(formData);
      const meetingDate = getFormMeetingDate(formData);
      const focalPerson = getFormFocalPerson(formData);
      const decision = getFormDecision(formData);
      const verificationSource = getFormVerificationSource(formData);
      const verificationLink = getFormVerificationLink(formData);

      if (!categoryId) {
        throw new Error(text.selectCategoryError);
      }

      if (!indicatorId) {
        throw new Error(text.selectIndicatorError);
      }

      if (!meetingDate) {
        throw new Error(text.selectMeetingDateError);
      }

      if (!focalPerson) {
        throw new Error(text.enterFocalPersonError);
      }

      if (!decision) {
        throw new Error(text.enterDecisionError);
      }

      if (!verificationSource) {
        throw new Error(text.enterVerificationSourceError);
      }
      
      const createdDecision = await createMinistryRgcDecision({
        plenaryId,
        categoryId,
        indicatorId,
        status,
        meetingDate,
        focalPerson,
        decision,
        verificationSource,
        verificationLink,
      });

      const rgcDecisionId = Number(createdDecision.id);

      if (!Number.isInteger(rgcDecisionId) || rgcDecisionId < 1) {
        throw new Error(text.createdDecisionIdMissing);
      }

      await submitRgcDecisionNotificationToCdc(rgcDecisionId);

      setSubmittedDecisionIds((current) => {
        const next = new Set(current);
        next.add(rgcDecisionId);
        return next;
      });

      window.dispatchEvent(new Event("system-notification-updated"));

      await refetch();

      closeCreateRgcDecisionDialog();

      setFeedback({
        severity: "success",
        message: text.sendSuccess,
      });
    } catch (sendError: unknown) {
      setFeedback({
        severity: "error",
        message: getErrorMessage(
          sendError,
          text.sendError,
        ),
      });
    } finally {
      setIsRgcSubmitting(false);
    }
  }

  if (!plenaryId || Number.isNaN(plenaryId)) {
    return (
      <Box
        sx={{
          minHeight: 420,
          display: "grid",
          placeItems: "center",
        }}
      >
        <Typography color="error">Invalid plenary ID.</Typography>
      </Box>
    );
  }

  if (loading) {
    return (
      <Box
        sx={{
          minHeight: 420,
          display: "grid",
          placeItems: "center",
        }}
      >
        <CircularProgress />
      </Box>
    );
  }

  if (error || !plenary) {
    return (
      <Box
        sx={{
          minHeight: "100%",
          px: { xs: 2, md: 4 },
          py: 4,
        }}
      >
        <Paper
          elevation={0}
          sx={{
            maxWidth: 560,
            mx: "auto",
            p: 4,
            textAlign: "center",
            borderRadius: 2.5,
            border: `1px solid ${theme.palette.divider}`,
            bgcolor: "background.paper",
          }}
        >
          <Typography variant="h6" sx={{ fontWeight: 800 }}>
            {text.plenaryRecordNotFound}
          </Typography>

          <Typography color="text.secondary" sx={{ mt: 1 }}>
            {error || text.plenaryRecordNotFoundDescription}
          </Typography>

          <Button
            variant="contained"
            onClick={() => router.push("/ministry/plenary/plenaries")}
            sx={{
              mt: 3,
              textTransform: "none",
            }}
          >
            {text.backToAllPlenaries}
          </Button>
        </Paper>
      </Box>
    );
  }

  const rgcDecisions = plenary.rgcDecisions ?? [];

  return (
    <>
      <Box
        sx={{
          minHeight: "100%",
          px: { xs: 2, sm: 3, lg: 4 },
          py: { xs: 2.5, md: 3.5 },
        }}
      >
        <Box
          sx={{
            display: "flex",
            flexWrap: "wrap",
            gap: 2,
            alignItems: "center",
            justifyContent: "space-between",
            mb: { xs: 3, md: 4 },
          }}
        >
          <Stack
            direction="row"
            spacing={2.5}
            sx={{
              minWidth: 0,
              alignItems: "center",
            }}
          >
            <Button
              size="small"
              startIcon={<ArrowBackRoundedIcon />}
              onClick={() => router.push("/ministry/plenary/plenaries")}
              sx={{
                p: 0,
                minWidth: 0,
                flexShrink: 0,
                textTransform: "none",
                color: "text.secondary",
              }}
            >
              Back
            </Button>

            <Box>
              <Typography
                variant="h5"
                sx={{
                  fontWeight: 800,
                  lineHeight: 1.25,
                }}
              >
                {text.plenaryDetail}
              </Typography>

              <Typography
                variant="body2"
                color="text.secondary"
                sx={{ mt: 0.45 }}
              >
                {text.plenaryDetailSubtitle}
              </Typography>
            </Box>
          </Stack>

          <Stack
            direction={{ xs: "column", sm: "row" }}
            spacing={1}
            sx={{
              width: { xs: "100%", sm: "auto" },
              alignItems: { xs: "stretch", sm: "center" },
            }}
          >
            <Button
              variant="contained"
              startIcon={<CheckRoundedIcon sx={{ fontSize: 17 }} />}
              disabled={isSubmittingToCdc || isRgcSubmitting}
              onClick={() => setSubmitDialogOpen(true)}
              sx={{
                minWidth: { xs: "100%", sm: 168 },
                height: 44,
                px: 2,
                borderRadius: "6px",
                textTransform: "none",
                fontSize: 12,
                fontWeight: 600,
                color: "#FFFFFF",
                bgcolor: "#1F6DB2",
                boxShadow: "none",

                "&:hover": {
                  bgcolor: "#155A98",
                  boxShadow: "none",
                },
              }}
            >
              {text.submitToCdc}
            </Button>

            <Button
              variant="contained"
              startIcon={<NoteAddOutlinedIcon sx={{ fontSize: 17 }} />}
              disabled={isSubmittingToCdc || isRgcSubmitting}
              onClick={() => {
                router.replace(
                  `/ministry/plenary/plenaries/${plenaryId}?createRgcDecision=1`,
                );
                setCreateRgcDecisionOpen(true);
              }}
              sx={{
                width: { xs: "100%", sm: 190 },
                minWidth: { xs: "100%", sm: 190 },
                height: 44,
                px: 2,
                borderRadius: "6px",
                textTransform: "none",
                fontSize: 12,
                fontWeight: 600,
                color: "#FFFFFF",
                bgcolor: "#1F6DB2",
                boxShadow: "none",

                "&:hover": {
                  bgcolor: "#155A98",
                  boxShadow: "none",
                },
              }}
            >
              {text.createRgcDecision}
            </Button>
          </Stack>
        </Box>

        <Box sx={{ mb: { xs: 3.5, md: 4 } }}>
          <Typography
            variant="h4"
            sx={{
              mb: { xs: 3, md: 3.5 },
              fontWeight: 800,
              fontSize: { xs: 25, md: 28 },
            }}
          >
            {plenary.name}
          </Typography>

          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: {
                xs: "1fr",
                md: "repeat(2, minmax(0, 1fr))",
              },
              columnGap: { md: 8, lg: 12 },
              rowGap: { xs: 3, md: 3.5 },
            }}
          >
            <Stack spacing={3.25}>
              <DetailItem
                icon={<CalendarMonthOutlinedIcon fontSize="small" />}
                label={text.deadlineLabel}
                value={plenary.deadline || "-"}
              />

              <DetailItem
                icon={<ScheduleOutlinedIcon fontSize="small" />}
                label={text.meetingDateLabel}
                value={plenary.meetingDate || "-"}
              />

              <DetailItem
                icon={<CheckRoundedIcon fontSize="small" />}
                label={text.statusLabel}
                value={<PlenaryStatusChip status={plenary.status} />}
              />
            </Stack>

            <Stack spacing={3.25}>
              <DetailItem
                icon={<ChatBubbleOutlineRoundedIcon fontSize="small" />}
                label={text.numberOfRgcDecision}
                value={rgcDecisions.length}
              />

              <DetailItem
                icon={<InsertDriveFileOutlinedIcon fontSize="small" />}
                label={text.attachment}
                value={
                  <PlenaryAttachment
                    name={plenary.documentName || text.plenaryDocument}
                    size={resolvedDocumentSize}
                    url={documentUrl}
                  />
                }
              />
            </Stack>
          </Box>
        </Box>

        <PlenaryDetailTable
          items={rgcDecisions}
          submittedDecisionIds={submittedDecisionIds}
        />
      </Box>

      <Dialog
        open={submitDialogOpen}
        onClose={() => {
          if (!isSubmittingToCdc) {
            setSubmitDialogOpen(false);
          }
        }}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle
          sx={{
            pt: 3,
            pb: 0.75,
            textAlign: "center",
            fontWeight: 800,
          }}
        >
          {text.submitToCdc}
        </DialogTitle>

        <DialogContent
          sx={{
            pt: "12px !important",
            textAlign: "center",
          }}
        >
          <Typography variant="body2" color="text.secondary">
            {text.submitDialogMessage}
          </Typography>
        </DialogContent>

        <DialogActions sx={{ gap: 1, px: 3, pb: 2.75 }}>
          <Button
            fullWidth
            variant="outlined"
            disabled={isSubmittingToCdc}
            onClick={() => setSubmitDialogOpen(false)}
            sx={{ textTransform: "none" }}
          >
            {text.cancel}
          </Button>

          <Button
            fullWidth
            variant="contained"
            disabled={isSubmittingToCdc}
            onClick={() => void handleSubmitToCdc()}
            sx={{ textTransform: "none" }}
          >
            {text.submit}
          </Button>
        </DialogActions>
      </Dialog>

      <CreateRgcDecisionDialog
        open={
          createRgcDecisionOpen ||
          createRgcDecisionRequested
        }
        onClose={() => {
          if (!isRgcSubmitting) {
            closeCreateRgcDecisionDialog();
          }
        }}
        onSaveDraft={handleSaveRgcDraft}
        onSendNotification={handleSendRgcNotification}
      />

      <Snackbar
        open={Boolean(feedback)}
        autoHideDuration={4000}
        onClose={() => setFeedback(null)}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "center",
        }}
      >
        <Alert
          severity={feedback?.severity ?? "success"}
          variant="filled"
          onClose={() => setFeedback(null)}
        >
          {feedback?.message}
        </Alert>
      </Snackbar>

      {isSubmittingToCdc || isRgcSubmitting ? (
        <SubmittingOverlay
          label={
            isRgcSubmitting
              ? text.savingRgcDecision
              : text.submittingRgcDecision
          }
        />
      ) : null}
    </>
  );
}

export default PlenaryDetailScreen;