"use client";

import { useCallback, useMemo, useState } from "react";

import { useRouter } from "next/navigation";

import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import CircularProgress from "@mui/material/CircularProgress";
import type { SxProps, Theme } from "@mui/material/styles";

import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import RateReviewOutlinedIcon from "@mui/icons-material/RateReviewOutlined";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { AlertDialog } from "@/components/ui/alert-dialog";
import { AppButton } from "@/components/ui/button";
import { ToastNotification } from "@/components/ui/toast-notification";
import { IssueStatusSelect } from "@/features/ministry/meeting-summary/components/create-meeting-summary/issue-status-select";
import { useIssueStatusOptions } from "@/features/ministry/meeting-summary/hook/use-issue-status-options";
import { ProgressReportPageContainer } from "@/features/ministry/progress-report/components/progress-report-page-container";
import { ProgressReportDecisionsSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-decisions-section";
import { ProgressReportDescriptionSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-description-section";
import { ProgressReportDetailHeader } from "@/features/ministry/progress-report/components/view-detail/progress-report-detail-header";
import { ProgressReportDetailInfoSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-detail-info-section";
import {
  ProgressReportIssueInfoDrawer,
} from "@/features/ministry/progress-report/components/view-detail/update-progress-report-issue-dialog";
import {
  ProgressReportAddCommentDrawer,
  ProgressReportEditCommentDrawer,
} from "@/features/ministry/progress-report/components/view-detail/progress-report-add-comment-drawer";
import { ProgressReportIssuesSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-issues-section";
import type { MinistryProgressReportIssueRow } from "@/features/ministry/progress-report/components/view-detail/progress-report-issues-data";
import type { MinistryProgressReportDecisionRow } from "@/features/ministry/progress-report/components/view-detail/progress-report-decisions-data";
import { ProgressReportRgcDecisionInfoDrawer } from "@/features/ministry/progress-report/components/view-detail/progress-report-rgc-decision-info-drawer";
import { ProgressReportDeleteCommentDialog } from "@/features/ministry/progress-report/components/view-detail/progress-report-delete-comment-dialog";

import {
  useProgressReportCommentTypes,
  useProgressReportIssueCommentMutations,
  useProgressReportMinistryDetail,
  useProgressReportRgcDecisionCommentMutations,
  useReviewProgressReportMinistry,
  useUpdateProgressReportMinistryIssueStatus,
  useUpdateProgressReportMinistryRgcDecisionStatus,
} from "../../../hook/use-progress-reports";
import {
  mapCdcMinistryIssues,
  mapCdcMinistryProgressReportDetail,
  mapCdcMinistryRgcDecisions,
} from "./progress-report-ministry-detail-mapper";
import { ProgressReportCommentActionsMenu } from "./progress-report-comment-actions-menu";
import { getRgcDecisionCommentActions } from "./progress-report-rgc-decision-comment-actions";

const reviewActionButtonSx: SxProps<Theme> = {
  height: 44,
  minHeight: 44,
  px: 1.5,
  bgcolor: "#1a64a8",
  color: "#ffffff",
  "& .MuiButton-startIcon": { m: 0, mr: 1 },
  "&:hover": { bgcolor: "#155489", boxShadow: "none" },
  "&.Mui-disabled": {
    bgcolor: "#bdbdbd",
    color: "#ffffff",
  },
};

type ProgressReportMinistryDetailScreenProps = {
  reportId: string;
  ministryId: string;
};

type PendingIssueStatusChange = {
  issueId: number;
  issueTitle: string;
  currentStatus: string;
  nextStatusId: number;
  nextStatusName: string;
};

type PendingReviewStatus = "CDC_UNDER_REVIEW" | "COMPLETED";

const issueStatusColors: Record<string, string> = {
  "In Progress": "#f79009",
  Solved: "#3ead46",
  "Not Addressed": "#f04438",
};

function IssueStatusHighlight({ status }: { status: string }) {
  return (
    <Box
      component="span"
      sx={{
        color: issueStatusColors[status] ?? "#475467",
        fontWeight: 600,
      }}
    >
      {status}
    </Box>
  );
}

function CdcIssueStatusSelect({
  row,
  disabled,
  onChangeRequest,
}: {
  row: MinistryProgressReportIssueRow;
  disabled: boolean;
  onChangeRequest: (change: PendingIssueStatusChange) => void;
}) {
  const { data: statusOptions = [] } = useIssueStatusOptions();

  function handleChange(statusName: string) {
    if (statusName === row.status) return;

    const selectedStatus = statusOptions.find(
      (status) => status.name.toLowerCase() === statusName.toLowerCase(),
    );

    if (!selectedStatus) return;

    onChangeRequest({
      issueId: row.id,
      issueTitle: row.issue,
      currentStatus: row.status,
      nextStatusId: selectedStatus.id,
      nextStatusName: selectedStatus.name,
    });
  }

  return (
    <IssueStatusSelect
      value={row.status}
      disabled={disabled}
      onChange={handleChange}
      variant="badge"
      sx={{ width: 168 }}
    />
  );
}

type PendingDecisionStatusChange = {
  plenaryDecisionId: number;
  category: string;
  currentStatus: string;
  nextStatus: "NOT_ADDRESSED" | "IN_PROGRESS" | "SOLVED";
  nextStatusName: string;
};

function decisionStatusToEnum(
  statusName: string,
): "NOT_ADDRESSED" | "IN_PROGRESS" | "SOLVED" {
  const normalized = statusName.trim().toLowerCase();
  if (normalized.startsWith("solve")) return "SOLVED";
  if (normalized.includes("progress")) return "IN_PROGRESS";
  return "NOT_ADDRESSED";
}

function CdcDecisionStatusSelect({
  row,
  disabled,
  onChangeRequest,
}: {
  row: MinistryProgressReportDecisionRow;
  disabled: boolean;
  onChangeRequest: (change: PendingDecisionStatusChange) => void;
}) {
  function handleChange(statusName: string) {
    if (statusName === row.status) return;

    onChangeRequest({
      plenaryDecisionId: row.id,
      category: row.category,
      currentStatus: row.status,
      nextStatus: decisionStatusToEnum(statusName),
      nextStatusName: statusName,
    });
  }

  return (
    <IssueStatusSelect
      value={row.status}
      disabled={disabled}
      onChange={handleChange}
      variant="badge"
      sx={{ width: 168 }}
    />
  );
}

export function ProgressReportMinistryDetailScreen({
  reportId,
  ministryId,
}: ProgressReportMinistryDetailScreenProps) {
  const router = useRouter();
  const { language } = useAppLanguage();
  const { assignment, isValidId, isLoading, error } =
    useProgressReportMinistryDetail(reportId, ministryId);
  const reviewReport = useReviewProgressReportMinistry(
    Number(reportId),
    Number(ministryId),
  );
  const updateIssueStatus = useUpdateProgressReportMinistryIssueStatus(
    Number(reportId),
    Number(ministryId),
  );
  const updateDecisionStatus = useUpdateProgressReportMinistryRgcDecisionStatus(
    Number(reportId),
    Number(ministryId),
  );
  const { commentTypes, error: commentTypesError } =
    useProgressReportCommentTypes();
  const issueCommentMutations = useProgressReportIssueCommentMutations(
    Number(reportId),
    Number(ministryId),
  );
  const decisionCommentMutations =
    useProgressReportRgcDecisionCommentMutations(
      Number(reportId),
      Number(ministryId),
    );
  const [pendingIssueStatusChange, setPendingIssueStatusChange] =
    useState<PendingIssueStatusChange | null>(null);
  const [pendingDecisionStatusChange, setPendingDecisionStatusChange] =
    useState<PendingDecisionStatusChange | null>(null);
  const [pendingReviewStatus, setPendingReviewStatus] =
    useState<PendingReviewStatus | null>(null);
  const [successMessage, setSuccessMessage] = useState("");

  const detail = useMemo(
    () =>
      assignment
        ? mapCdcMinistryProgressReportDetail(assignment, language)
        : null,
    [assignment, language],
  );
  const issueRows = useMemo(
    () => (assignment ? mapCdcMinistryIssues(assignment) : []),
    [assignment],
  );
  const decisionRows = useMemo(
    () => (assignment ? mapCdcMinistryRgcDecisions(assignment) : []),
    [assignment],
  );
  const [viewIssue, setViewIssue] =
    useState<MinistryProgressReportIssueRow | null>(null);
  const [viewDecision, setViewDecision] =
    useState<MinistryProgressReportDecisionRow | null>(null);
  const [commentIssue, setCommentIssue] =
    useState<MinistryProgressReportIssueRow | null>(null);
  const [commentDecision, setCommentDecision] =
    useState<MinistryProgressReportDecisionRow | null>(null);
  const [editCommentIssue, setEditCommentIssue] =
    useState<MinistryProgressReportIssueRow | null>(null);
  const [editCommentDecision, setEditCommentDecision] =
    useState<MinistryProgressReportDecisionRow | null>(null);
  const [deleteCommentIssue, setDeleteCommentIssue] =
    useState<MinistryProgressReportIssueRow | null>(null);
  const [deleteCommentDecision, setDeleteCommentDecision] =
    useState<MinistryProgressReportDecisionRow | null>(null);

  const openAddComment = useCallback(
    (row: MinistryProgressReportIssueRow) => {
      issueCommentMutations.createComment.reset();
      setViewIssue(null);
      setViewDecision(null);
      setEditCommentIssue(null);
      setEditCommentDecision(null);
      setCommentDecision(null);
      setCommentIssue(row);
    },
    [issueCommentMutations.createComment],
  );

  const openAddDecisionComment = useCallback(
    (row: MinistryProgressReportDecisionRow) => {
      decisionCommentMutations.createComment.reset();
      setViewIssue(null);
      setViewDecision(null);
      setEditCommentIssue(null);
      setEditCommentDecision(null);
      setCommentIssue(null);
      setCommentDecision(row);
    },
    [decisionCommentMutations.createComment],
  );

  const openEditComment = useCallback(
    (row: MinistryProgressReportIssueRow) => {
      issueCommentMutations.updateComment.reset();
      setViewIssue(null);
      setViewDecision(null);
      setCommentIssue(null);
      setCommentDecision(null);
      setEditCommentDecision(null);
      setEditCommentIssue(row);
    },
    [issueCommentMutations.updateComment],
  );

  const openEditDecisionComment = useCallback(
    (row: MinistryProgressReportDecisionRow) => {
      decisionCommentMutations.updateComment.reset();
      setViewIssue(null);
      setViewDecision(null);
      setCommentIssue(null);
      setCommentDecision(null);
      setEditCommentIssue(null);
      setDeleteCommentIssue(null);
      setDeleteCommentDecision(null);
      setEditCommentDecision(row);
    },
    [decisionCommentMutations.updateComment],
  );

  const openDeleteIssueComment = useCallback(
    (row: MinistryProgressReportIssueRow) => {
      issueCommentMutations.deleteComment.reset();
      setViewIssue(null);
      setViewDecision(null);
      setCommentIssue(null);
      setCommentDecision(null);
      setEditCommentIssue(null);
      setEditCommentDecision(null);
      setDeleteCommentDecision(null);
      setDeleteCommentIssue(row);
    },
    [issueCommentMutations.deleteComment],
  );

  const openDeleteDecisionComment = useCallback(
    (row: MinistryProgressReportDecisionRow) => {
      decisionCommentMutations.deleteComment.reset();
      setViewIssue(null);
      setViewDecision(null);
      setCommentIssue(null);
      setCommentDecision(null);
      setEditCommentIssue(null);
      setEditCommentDecision(null);
      setDeleteCommentIssue(null);
      setDeleteCommentDecision(row);
    },
    [decisionCommentMutations.deleteComment],
  );

  const handleConfirmDeleteComment = useCallback(async () => {
    if (deleteCommentIssue?.cdcComment) {
      try {
        await issueCommentMutations.deleteComment.mutateAsync({
          issueId: deleteCommentIssue.id,
          commentId: deleteCommentIssue.cdcComment.id,
        });
        setSuccessMessage("Issue comment deleted successfully.");
        issueCommentMutations.deleteComment.reset();
        setDeleteCommentIssue(null);
      } catch {
        // Keep the dialog open so CDC can read the backend error and retry.
      }
      return;
    }

    if (deleteCommentDecision?.cdcComment) {
      try {
        await decisionCommentMutations.deleteComment.mutateAsync({
          plenaryDecisionId: deleteCommentDecision.id,
          commentId: deleteCommentDecision.cdcComment.id,
        });
        setSuccessMessage("RGC Decision comment deleted successfully.");
        decisionCommentMutations.deleteComment.reset();
        setDeleteCommentDecision(null);
      } catch {
        // Keep the dialog open so CDC can read the backend error and retry.
      }
    }
  }, [
    decisionCommentMutations.deleteComment,
    deleteCommentDecision,
    deleteCommentIssue,
    issueCommentMutations.deleteComment,
  ]);

  const renderIssueCommentActions = useCallback(
    (row: MinistryProgressReportIssueRow) => (
      <ProgressReportCommentActionsMenu
        onViewDetail={() => setViewIssue(row)}
        onAddComment={
          row.cdcComment ? undefined : () => openAddComment(row)
        }
        onEditComment={
          row.cdcComment ? () => openEditComment(row) : undefined
        }
        onDeleteComment={
          row.cdcComment ? () => openDeleteIssueComment(row) : undefined
        }
      />
    ),
    [openAddComment, openDeleteIssueComment, openEditComment],
  );

  const renderDecisionCommentActions = useCallback(
    (row: MinistryProgressReportDecisionRow) => {
      const actions = getRgcDecisionCommentActions({
        hasProgressUpdate: Boolean(row.hasProgressUpdate),
        hasComment: Boolean(row.cdcComment),
      });

      return (
        <ProgressReportCommentActionsMenu
          onViewDetail={() => setViewDecision(row)}
          onAddComment={
            actions.showAdd ? () => openAddDecisionComment(row) : undefined
          }
          addCommentDisabled={!actions.canAdd}
          addCommentDisabledReason="The Ministry must save this RGC Decision progress update first."
          onEditComment={
            actions.canEdit ? () => openEditDecisionComment(row) : undefined
          }
          onDeleteComment={
            actions.canDelete
              ? () => openDeleteDecisionComment(row)
              : undefined
          }
        />
      );
    },
    [openAddDecisionComment, openDeleteDecisionComment, openEditDecisionComment],
  );

  const renderIssueStatus = useCallback(
    (row: MinistryProgressReportIssueRow) => (
      <CdcIssueStatusSelect
        row={row}
        disabled={
          updateIssueStatus.isPending ||
          (assignment?.status !== "SUBMITTED" &&
            assignment?.status !== "CDC_UNDER_REVIEW")
        }
        onChangeRequest={(change) => {
          updateIssueStatus.reset();
          setPendingIssueStatusChange(change);
        }}
      />
    ),
    [assignment?.status, updateIssueStatus],
  );

  const cancelIssueStatusChange = useCallback(() => {
    if (updateIssueStatus.isPending) return;

    updateIssueStatus.reset();
    setPendingIssueStatusChange(null);
  }, [updateIssueStatus]);

  const confirmIssueStatusChange = useCallback(async () => {
    if (!pendingIssueStatusChange || updateIssueStatus.isPending) return;

    try {
      await updateIssueStatus.mutateAsync({
        issueId: pendingIssueStatusChange.issueId,
        issueStatusId: pendingIssueStatusChange.nextStatusId,
      });
      setSuccessMessage(
        `Issue status changed to ${pendingIssueStatusChange.nextStatusName} successfully.`,
      );
      updateIssueStatus.reset();
      setPendingIssueStatusChange(null);
    } catch {
      // Keep the dialog open so CDC can read the backend error and retry.
    }
  }, [pendingIssueStatusChange, updateIssueStatus]);

  const renderDecisionStatus = useCallback(
    (row: MinistryProgressReportDecisionRow) => (
      <CdcDecisionStatusSelect
        row={row}
        disabled={
          updateDecisionStatus.isPending ||
          (assignment?.status !== "SUBMITTED" &&
            assignment?.status !== "CDC_UNDER_REVIEW")
        }
        onChangeRequest={(change) => {
          updateDecisionStatus.reset();
          setPendingDecisionStatusChange(change);
        }}
      />
    ),
    [assignment?.status, updateDecisionStatus],
  );

  const cancelDecisionStatusChange = useCallback(() => {
    if (updateDecisionStatus.isPending) return;

    updateDecisionStatus.reset();
    setPendingDecisionStatusChange(null);
  }, [updateDecisionStatus]);

  const confirmDecisionStatusChange = useCallback(async () => {
    if (!pendingDecisionStatusChange || updateDecisionStatus.isPending) return;

    try {
      await updateDecisionStatus.mutateAsync({
        plenaryDecisionId: pendingDecisionStatusChange.plenaryDecisionId,
        status: pendingDecisionStatusChange.nextStatus,
      });
      setSuccessMessage(
        `RGC Decision status changed to ${pendingDecisionStatusChange.nextStatusName} successfully.`,
      );
      updateDecisionStatus.reset();
      setPendingDecisionStatusChange(null);
    } catch {
      // Keep the dialog open so CDC can read the backend error and retry.
    }
  }, [pendingDecisionStatusChange, updateDecisionStatus]);

  const openReviewConfirmation = useCallback(
    (status: PendingReviewStatus) => {
      if (reviewReport.isPending) return;

      reviewReport.reset();
      setPendingReviewStatus(status);
    },
    [reviewReport],
  );

  const cancelReviewConfirmation = useCallback(() => {
    if (reviewReport.isPending) return;

    reviewReport.reset();
    setPendingReviewStatus(null);
  }, [reviewReport]);

  const confirmReviewStatusChange = useCallback(async () => {
    if (!pendingReviewStatus || reviewReport.isPending) return;

    try {
      await reviewReport.mutateAsync(pendingReviewStatus);
      setSuccessMessage(
        pendingReviewStatus === "CDC_UNDER_REVIEW"
          ? "Progress report review started successfully."
          : "Progress report completed successfully.",
      );
      reviewReport.reset();
      setPendingReviewStatus(null);
    } catch {
      // Keep the dialog open so CDC can read the backend error and retry.
    }
  }, [pendingReviewStatus, reviewReport]);

  const reviewDialogTitle =
    pendingReviewStatus === "CDC_UNDER_REVIEW"
      ? "Start Progress Report Review"
      : "Complete Progress Report";

  const reviewDialogDescription =
    pendingReviewStatus === "CDC_UNDER_REVIEW"
      ? "Are you sure you want to start reviewing this progress report?"
      : "Are you sure you want to complete this progress report?";

  if (isLoading) {
    return (
      <ProgressReportPageContainer>
        <Box
          sx={{
            minHeight: 320,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <CircularProgress />
        </Box>
      </ProgressReportPageContainer>
    );
  }

  if (!isValidId || error || !assignment || !detail) {
    const message = !isValidId
      ? "Invalid progress report or Ministry ID."
      : error || "Ministry progress report not found.";

    return (
      <ProgressReportPageContainer>
        <Alert severity="error">{message}</Alert>
      </ProgressReportPageContainer>
    );
  }

  return (
    <ProgressReportPageContainer>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          gap: 3,
          width: "100%",
          maxWidth: "100%",
          overflowX: "hidden",
        }}
      >
        <ProgressReportDetailHeader
          readOnly
          title={detail.title}
          ministryName={detail.ministryName}
          ministryLogo={detail.ministryLogo}
          onBack={() => router.push(`/cdc-gpsf/progress-reports/${reportId}`)}
          actionSlot={
            assignment.status === "SUBMITTED" ? (
              <AppButton
                disabled={reviewReport.isPending}
                onClick={() =>
                  openReviewConfirmation("CDC_UNDER_REVIEW")
                }
                startIcon={<RateReviewOutlinedIcon sx={{ fontSize: 24 }} />}
                sx={reviewActionButtonSx}
              >
                Start Review
              </AppButton>
            ) : assignment.status === "CDC_UNDER_REVIEW" ? (
              <AppButton
                disabled={reviewReport.isPending}
                onClick={() => openReviewConfirmation("COMPLETED")}
                startIcon={<CheckRoundedIcon sx={{ fontSize: 24 }} />}
                sx={reviewActionButtonSx}
              >
                Complete
              </AppButton>
            ) : null
          }
        />

        {reviewReport.error ? (
          <Alert severity="error">
            {reviewReport.error instanceof Error
              ? reviewReport.error.message
              : "Unable to update the review status."}
          </Alert>
        ) : null}

        <ProgressReportDetailInfoSection detail={detail} />
        <ProgressReportDescriptionSection description={detail.description} />
        <ProgressReportIssuesSection
          rows={issueRows}
          renderStatus={renderIssueStatus}
          renderAction={renderIssueCommentActions}
        />
        <ProgressReportDecisionsSection
          rows={decisionRows}
          renderStatus={renderDecisionStatus}
          renderAction={renderDecisionCommentActions}
        />

        <ProgressReportIssueInfoDrawer
          open={Boolean(viewIssue)}
          issue={viewIssue}
          issueAttachment={viewIssue?.progressUpdateAttachment ?? null}
          onClose={() => setViewIssue(null)}
          onAddComment={
            viewIssue && viewIssue.hasProgressUpdate && !viewIssue.cdcComment
              ? () => openAddComment(viewIssue)
              : undefined
          }
        />

        <ProgressReportRgcDecisionInfoDrawer
          open={Boolean(viewDecision)}
          decision={viewDecision}
          decisionAttachment={viewDecision?.progressUpdateAttachment ?? null}
          onClose={() => setViewDecision(null)}
          onAddComment={
            viewDecision?.hasProgressUpdate && !viewDecision.cdcComment
              ? () => openAddDecisionComment(viewDecision)
              : undefined
          }
        />

        <ProgressReportAddCommentDrawer
          open={Boolean(commentIssue || commentDecision)}
          issue={commentIssue}
          decision={commentDecision}
          commentTypes={commentTypes}
          error={
            commentIssue
              ? issueCommentMutations.createComment.error instanceof Error
                ? issueCommentMutations.createComment.error.message
                : commentTypesError
              : decisionCommentMutations.createComment.error instanceof Error
                ? decisionCommentMutations.createComment.error.message
                : commentTypesError
          }
          onClose={() => {
            issueCommentMutations.createComment.reset();
            decisionCommentMutations.createComment.reset();
            setCommentIssue(null);
            setCommentDecision(null);
          }}
          onSave={async ({
            issue,
            decision,
            commentTypeId,
            comment,
          }) => {
            if (!commentTypeId) {
              throw new Error("Please select a valid comment type.");
            }

            if (issue) {
              await issueCommentMutations.createComment.mutateAsync({
                issueId: issue.id,
                commentTypeId,
                comment,
              });
              setSuccessMessage("Issue comment added successfully.");
            }
            if (decision) {
              await decisionCommentMutations.createComment.mutateAsync({
                plenaryDecisionId: decision.id,
                commentTypeId,
                comment,
              });
              setSuccessMessage("RGC Decision comment added successfully.");
            }
          }}
        />

        <ProgressReportEditCommentDrawer
          open={Boolean(editCommentIssue || editCommentDecision)}
          issue={editCommentIssue}
          decision={editCommentDecision}
          commentTypes={commentTypes}
          error={
            editCommentIssue
              ? issueCommentMutations.updateComment.error instanceof Error
                ? issueCommentMutations.updateComment.error.message
                : commentTypesError
              : decisionCommentMutations.updateComment.error instanceof Error
                ? decisionCommentMutations.updateComment.error.message
                : commentTypesError
          }
          initialComment={
            editCommentIssue?.cdcComment
              ? {
                  id: editCommentIssue.cdcComment.id,
                  commentTypeId: editCommentIssue.cdcComment.commentTypeId,
                  commentType: editCommentIssue.cdcComment.commentType.name,
                  comment: editCommentIssue.cdcComment.comment,
                }
              : editCommentDecision?.cdcComment
                ? {
                    id: editCommentDecision.cdcComment.id,
                    commentTypeId:
                      editCommentDecision.cdcComment.commentTypeId,
                    commentType:
                      editCommentDecision.cdcComment.commentType.name,
                    comment: editCommentDecision.cdcComment.comment,
                  }
                : null
          }
          onClose={() => {
            issueCommentMutations.updateComment.reset();
            decisionCommentMutations.updateComment.reset();
            setEditCommentIssue(null);
            setEditCommentDecision(null);
          }}
          onSave={async ({
            issue,
            decision,
            commentTypeId,
            comment,
          }) => {
            if (issue) {
              const commentId = issue.cdcComment?.id;
              if (!commentId || !commentTypeId) {
                throw new Error("The saved Issue comment was not found.");
              }

              await issueCommentMutations.updateComment.mutateAsync({
                issueId: issue.id,
                commentId,
                commentTypeId,
                comment,
              });
              setSuccessMessage("Issue comment updated successfully.");
            }
            if (decision) {
              const commentId = decision.cdcComment?.id;
              if (!commentId || !commentTypeId) {
                throw new Error(
                  "The saved RGC Decision comment was not found.",
                );
              }

              await decisionCommentMutations.updateComment.mutateAsync({
                plenaryDecisionId: decision.id,
                commentId,
                commentTypeId,
                comment,
              });
              setSuccessMessage(
                "RGC Decision comment updated successfully.",
              );
            }
          }}
        />

        <ProgressReportDeleteCommentDialog
          open={Boolean(deleteCommentIssue || deleteCommentDecision)}
          loading={
            issueCommentMutations.deleteComment.isPending ||
            decisionCommentMutations.deleteComment.isPending
          }
          error={
            deleteCommentIssue &&
            issueCommentMutations.deleteComment.error instanceof Error
              ? issueCommentMutations.deleteComment.error.message
              : deleteCommentDecision &&
                  decisionCommentMutations.deleteComment.error instanceof Error
                ? decisionCommentMutations.deleteComment.error.message
                : null
          }
          onClose={() => {
            if (
              issueCommentMutations.deleteComment.isPending ||
              decisionCommentMutations.deleteComment.isPending
            ) {
              return;
            }

            issueCommentMutations.deleteComment.reset();
            decisionCommentMutations.deleteComment.reset();
            setDeleteCommentIssue(null);
            setDeleteCommentDecision(null);
          }}
          onConfirm={handleConfirmDeleteComment}
        />

        <AlertDialog
          open={Boolean(pendingReviewStatus)}
          title={reviewDialogTitle}
          description={
            pendingReviewStatus ? (
              <>
                {reviewDialogDescription}
                {reviewReport.error ? (
                  <Box
                    component="span"
                    sx={{
                      display: "block",
                      mt: 1.5,
                      color: "#d92d20",
                    }}
                  >
                    {reviewReport.error instanceof Error
                      ? reviewReport.error.message
                      : "Unable to update the review status."}
                  </Box>
                ) : null}
              </>
            ) : undefined
          }
          confirmLabel="Confirm"
          cancelLabel="Cancel"
          loading={reviewReport.isPending}
          onConfirm={() => void confirmReviewStatusChange()}
          onCancel={cancelReviewConfirmation}
        />

        <AlertDialog
          open={Boolean(pendingIssueStatusChange)}
          title="Change Issue Status"
          description={
            pendingIssueStatusChange ? (
              <>
                Are you sure you want to change &quot;
                {pendingIssueStatusChange.issueTitle}&quot; from{" "}
                <IssueStatusHighlight
                  status={pendingIssueStatusChange.currentStatus}
                />{" "}
                to{" "}
                <IssueStatusHighlight
                  status={pendingIssueStatusChange.nextStatusName}
                />
                ?
                {updateIssueStatus.error ? (
                  <Box
                    component="span"
                    sx={{
                      display: "block",
                      mt: 1.5,
                      color: "#d92d20",
                    }}
                  >
                    {updateIssueStatus.error instanceof Error
                      ? updateIssueStatus.error.message
                      : "Unable to update the Issue status."}
                  </Box>
                ) : null}
              </>
            ) : undefined
          }
          confirmLabel="Confirm"
          cancelLabel="Cancel"
          loading={updateIssueStatus.isPending}
          onConfirm={() => void confirmIssueStatusChange()}
          onCancel={cancelIssueStatusChange}
        />

        <AlertDialog
          open={Boolean(pendingDecisionStatusChange)}
          title="Change RGC Decision Status"
          description={
            pendingDecisionStatusChange ? (
              <>
                Are you sure you want to change the &quot;
                {pendingDecisionStatusChange.category}&quot; RGC decision from{" "}
                <IssueStatusHighlight
                  status={pendingDecisionStatusChange.currentStatus}
                />{" "}
                to{" "}
                <IssueStatusHighlight
                  status={pendingDecisionStatusChange.nextStatusName}
                />
                ?
                {updateDecisionStatus.error ? (
                  <Box
                    component="span"
                    sx={{
                      display: "block",
                      mt: 1.5,
                      color: "#d92d20",
                    }}
                  >
                    {updateDecisionStatus.error instanceof Error
                      ? updateDecisionStatus.error.message
                      : "Unable to update the RGC Decision status."}
                  </Box>
                ) : null}
              </>
            ) : undefined
          }
          confirmLabel="Confirm"
          cancelLabel="Cancel"
          loading={updateDecisionStatus.isPending}
          onConfirm={() => void confirmDecisionStatusChange()}
          onCancel={cancelDecisionStatusChange}
        />

        <ToastNotification
          open={Boolean(successMessage)}
          message={successMessage}
          onClose={() => setSuccessMessage("")}
        />
      </Box>
    </ProgressReportPageContainer>
  );
}

export default ProgressReportMinistryDetailScreen;
