"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 Button from "@mui/material/Button";
import Snackbar from "@mui/material/Snackbar";
import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import { alpha, useTheme } from "@mui/material/styles";

import { EyeViewIcon } from "@/components/ui/icon";
import { useAppLanguage } from "@/components/providers/app-language-provider";
import { AlertDialog } from "@/components/ui/alert-dialog";
import { ToastNotification } from "@/components/ui/toast-notification";
import { ProgressReportDetailHeader } from "@/features/ministry/progress-report/components/view-detail/progress-report-detail-header";
import { ProgressReportDescriptionSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-description-section";
import { ProgressReportDetailInfoSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-detail-info-section";
import { ProgressReportIssuesSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-issues-section";
import { IssuesUpdateActionCell } from "@/features/ministry/progress-report/components/view-detail/progress-report-issues-cells";
import type { MinistryProgressReportIssueRow } from "@/features/ministry/progress-report/components/view-detail/progress-report-issues-data";
import { ProgressReportIssueInfoDrawer } from "@/features/ministry/progress-report/components/view-detail/update-progress-report-issue-dialog";
import { ProgressReportDecisionsSection } from "@/features/ministry/progress-report/components/view-detail/progress-report-decisions-section";
import {
  usePswgProgressReport,
  useReviewPswgProgressReport,
} from "@/features/pswg/progress-report/hook/use-progress-reports";
import {
  mapPswgIssuesToRows,
  mapPswgProgressReportDetail,
  mapPswgRgcDecisionsToRows,
} from "@/features/pswg/progress-report/progress-report-detail-data";

import { ProgressReportPageContainer } from "../progress-report-page-container";
import { ProgressReportEvaluationDrawer } from "./progress-report-evaluation-drawer";

type Props = { id: string };

export function ProgressReportViewDetails({ id }: Props) {
  const router = useRouter();
  const theme = useTheme();
  const { language } = useAppLanguage();
  const { assignment, isValidId, isLoading, error } = usePswgProgressReport(id);
  const assignmentId = Number(id);
  const reviewReport = useReviewPswgProgressReport(assignmentId);
  const [evaluationOpen, setEvaluationOpen] = useState(false);
  const [evaluationSubmitted, setEvaluationSubmitted] = useState(false);
  const [reviewDialogOpen, setReviewDialogOpen] = useState(false);
  const [reviewError, setReviewError] = useState<string | null>(null);
  const [reviewSuccessOpen, setReviewSuccessOpen] = useState(false);
  const [viewIssue, setViewIssue] =
    useState<MinistryProgressReportIssueRow | null>(null);

  // Confirm the review from the dialog. On failure we keep the dialog open
  // and show the message inside it, matching the ministry "Submit to CDC" flow.
  async function handleReviewConfirm() {
    setReviewError(null);

    try {
      await reviewReport.mutateAsync();
      setReviewDialogOpen(false);
      setReviewSuccessOpen(true);
    } catch (error) {
      setReviewError(
        error instanceof Error
          ? error.message
          : "Unable to review this progress report.",
      );
    }
  }
  const detail = useMemo(
    () =>
      assignment ? mapPswgProgressReportDetail(assignment, language) : null,
    [assignment, language],
  );
  const issueRows = useMemo(
    () => (assignment ? mapPswgIssuesToRows(assignment) : []),
    [assignment],
  );
  const decisionRows = useMemo(
    () => (assignment ? mapPswgRgcDecisionsToRows(assignment) : []),
    [assignment],
  );
  const renderIssueAction = useCallback(
    (row: MinistryProgressReportIssueRow) => (
      <IssuesUpdateActionCell
        label="View Issue"
        icon={<EyeViewIcon sx={{ fontSize: 24 }} />}
        onUpdate={() => setViewIssue(row)}
      />
    ),
    [],
  );

  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 assignment ID."
      : error || "Progress report assignment 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("/pswg/progress-report")}
          actionSlot={
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                gap: "22px",
                flexWrap: "wrap",
              }}
            >
              <Button
                variant="outlined"
                onClick={() => setEvaluationOpen(true)}
                sx={{
                  height: 44,
                  minWidth: 119,
                  px: 1.5,
                  py: 1.25,
                  borderRadius: "6px",
                  textTransform: "none",
                  fontSize: 13,
                  fontWeight: 500,
                  borderColor: "#1a64a8",
                  color: "#1a64a8",
                  bgcolor:
                    theme.palette.mode === "dark"
                      ? alpha("#1a64a8", 0.16)
                      : "#edf8fd",
                  "&:hover": {
                    borderColor: "#1a64a8",
                    bgcolor:
                      theme.palette.mode === "dark"
                        ? alpha("#1a64a8", 0.24)
                        : alpha("#1a64a8", 0.1),
                  },
                }}
              >
                Evaluation Link
              </Button>

              <Button
                variant="contained"
                startIcon={<CheckRoundedIcon sx={{ fontSize: 24 }} />}
                disabled={
                  assignment.status !== "SHARED_WITH_PSWG" ||
                  reviewReport.isPending
                }
                onClick={() => {
                  setReviewError(null);
                  setReviewDialogOpen(true);
                }}
                sx={{
                  height: 44,
                  minWidth: 119,
                  px: 1.5,
                  py: 1.25,
                  borderRadius: "6px",
                  textTransform: "none",
                  fontSize: 13,
                  fontWeight: 500,
                  bgcolor: "#1a64a8",
                  boxShadow: "none",
                  "& .MuiButton-startIcon": { m: 0, mr: "10px" },
                  "&:hover": {
                    bgcolor: "#155489",
                    boxShadow: "none",
                  },
                  "&.Mui-disabled": {
                    bgcolor: "#bdbdbd",
                    color: "#ffffff",
                  },
                }}
              >
                Reviewed
              </Button>
            </Box>
          }
        />

        <ProgressReportDetailInfoSection detail={detail} />

        <ProgressReportDescriptionSection description={detail.description} />

        <ProgressReportIssuesSection
          rows={issueRows}
          renderAction={renderIssueAction}
        />
        <ProgressReportDecisionsSection rows={decisionRows} />
      </Box>

      <AlertDialog
        open={reviewDialogOpen}
        title="Review Progress Report"
        description={
          <Box>
            <Box>
              Are you sure you want to mark this progress report as reviewed?
            </Box>
            {reviewError ? (
              <Box sx={{ mt: 1, color: "#d92d20" }}>{reviewError}</Box>
            ) : null}
          </Box>
        }
        confirmLabel="Confirm"
        cancelLabel="Cancel"
        loading={reviewReport.isPending}
        onConfirm={() => void handleReviewConfirm()}
        onCancel={() => setReviewDialogOpen(false)}
      />

      <ProgressReportEvaluationDrawer
        open={evaluationOpen}
        onClose={() => setEvaluationOpen(false)}
        onSubmit={async () => {
          setEvaluationSubmitted(true);
        }}
      />

      <ProgressReportIssueInfoDrawer
        open={Boolean(viewIssue)}
        issue={viewIssue}
        onClose={() => setViewIssue(null)}
        issueAttachment={viewIssue?.progressUpdateAttachment ?? null}
      />

      <Snackbar
        open={evaluationSubmitted}
        autoHideDuration={3000}
        onClose={() => setEvaluationSubmitted(false)}
        message="Evaluation submitted successfully."
        anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
      />

      <ToastNotification
        open={reviewSuccessOpen}
        message="Progress report reviewed successfully."
        onClose={() => setReviewSuccessOpen(false)}
      />
    </ProgressReportPageContainer>
  );
}

export default ProgressReportViewDetails;
