"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";

import Box from "@mui/material/Box";
import CircularProgress from "@mui/material/CircularProgress";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";

import { ToastNotification } from "@/components/ui/toast-notification";
import { getMeetingSummaryFont } from "../../meeting-summary-i18n";
import {
  getMeetingSummaryById,
  shareMeetingSummaryWithPswg,
} from "../../meeting-summary-service";
import type { ViewMeetingSummaryDetail } from "./view-meeting-summary-data";
import { ViewMeetingSummaryHeader } from "./view-meeting-summary-header";
import { ViewMeetingSummaryInfoSection } from "./view-meeting-summary-info-section";
import { IssueListTable } from "./issue-list-table";
import { MeetingSummaryParticipantsTable } from "../meeting-summary-participants-table";

import { printMeetingSummaryLayout } from "./print/meeting-summary-print-action";
import { buildMeetingSummaryPrintModel } from "./print/meeting-summary-print-mock-data";
import { MeetingSummaryPrintView } from "./print/meeting-summary-print-view";
import { ViewMeetingSummaryReferenceSection } from "./view-meeting-summary-reference-section";
import { ViewMeetingSummaryIssueDetailDialog } from "./view-meeting-summary-issue-detail-dialog";
import type { ViewMeetingSummaryIssueRow } from "./view-meeting-summary-data";

type Props = {
  summaryId: number;
  lang?: "en" | "km";
};

export function ViewMeetingSummaryScreen({ summaryId, lang = "en" }: Props) {
  const router = useRouter();
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const isInvalidSummaryId = !Number.isFinite(summaryId) || summaryId <= 0;

  const [detail, setDetail] = useState<ViewMeetingSummaryDetail | null>(null);
  const [fetchLoading, setFetchLoading] = useState(!isInvalidSummaryId);
  const [fetchError, setFetchError] = useState<string | null>(null);
  const loading = isInvalidSummaryId ? false : fetchLoading;
  const error = isInvalidSummaryId ? "Meeting summary not found." : fetchError;
  const [selectedIssue, setSelectedIssue] =
    useState<ViewMeetingSummaryIssueRow | null>(null);
  const [sharing, setSharing] = useState(false);
  const [toast, setToast] = useState<string | null>(null);
  const printModel = useMemo(
    () => buildMeetingSummaryPrintModel(detail, { useMockIssues: true }),
    [detail],
  );

  async function handleShareToggle() {
    if (isInvalidSummaryId || sharing || !detail || detail.share) return;

    setSharing(true);
    try {
      await shareMeetingSummaryWithPswg(summaryId);
      setToast("Shared with PSWG.");
      setDetail((current) =>
        current ? { ...current, share: true } : current,
      );
    } catch {
      setToast("Could not share with PSWG. Please try again.");
    } finally {
      setSharing(false);
    }
  }

  useEffect(() => {
    if (isInvalidSummaryId) return;

    let cancelled = false;

    async function loadSummary() {
      setFetchLoading(true);
      setFetchError(null);

      try {
        const data = await getMeetingSummaryById(summaryId);
        if (cancelled) return;
        setDetail(data);
      } catch {
        if (cancelled) return;
        setFetchError("Could not load meeting summary.");
      } finally {
        if (!cancelled) setFetchLoading(false);
      }
    }

    void loadSummary();

    return () => {
      cancelled = true;
    };
  }, [isInvalidSummaryId, summaryId]);

  return (
    <Box
      sx={{
        "--ms-text": isDark ? "#E5E7EB" : "#181d27",
        "--ms-muted": isDark ? "#CBD5E1" : "#717680",
        "--ms-subtle": isDark ? "#9CA3AF" : "#414651",
        "--ms-secondary": isDark ? "#E5E7EB" : "#252b37",
        "--ms-border": isDark ? "#374151" : "#e9eaeb",
        "--ms-blue": isDark ? "#60A5FA" : "#1a64a8",
        "--ms-blue-dark": isDark ? "#3B82F6" : "#155489",
        "--ms-chip-bg": isDark ? "#1E3A5F" : "#edf8fd",
        "--ms-chip-border": isDark ? "#4D87C7" : "#b6dbf6",
        "--ms-surface": isDark ? "#111827" : "#fafafa",
        "--ms-surface-track": isDark ? "#1F2937" : "#ffffff",
        minHeight: "100%",
        width: "100%",
        minWidth: 0,
        px: { xs: 2, md: 3 },
        py: { xs: 2, md: 3 },
        color: "var(--ms-text)",
        fontFamily: getMeetingSummaryFont(lang),
        overflowX: "hidden",
      }}
    >
      <ViewMeetingSummaryHeader
        onBack={() => router.push("/ministry/meeting-summary")}
        shared={detail?.share ?? false}
        onShareConfirm={handleShareToggle}
      />

      {loading ? (
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            minHeight: 320,
          }}
        >
          <CircularProgress size={32} />
        </Box>
      ) : error || !detail ? (
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            minHeight: 320,
          }}
        >
          <Typography sx={{ fontSize: 14, color: "var(--ms-muted)" }}>
            {error ?? "Meeting summary not found."}
          </Typography>
        </Box>
      ) : (
        <>
          <ViewMeetingSummaryInfoSection detail={detail} />

          <IssueListTable
            rows={detail.issues}
            onPrint={printMeetingSummaryLayout}
            onViewIssue={setSelectedIssue}
          />

          <MeetingSummaryParticipantsTable participants={detail.participants} />

          <MeetingSummaryPrintView model={printModel} />

          <ViewMeetingSummaryReferenceSection
            reference={detail.summaryReference}
          />

          <ViewMeetingSummaryIssueDetailDialog
            open={Boolean(selectedIssue)}
            issue={selectedIssue}
            submittedBy={detail.sentBy}
            submittedDate={detail.date}
            issueDocument={detail.meetingRequestDocument}
            issueDocumentSize={detail.meetingRequestDocumentSize}
            onClose={() => setSelectedIssue(null)}
          />
        </>
      )}

      <ToastNotification
        open={Boolean(toast)}
        message={toast ?? ""}
        onClose={() => setToast(null)}
      />
    </Box>
  );
}
