"use client";

import type { ReactNode } from "react";
import { 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 PictureAsPdfOutlinedIcon from "@mui/icons-material/PictureAsPdfOutlined";
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 { 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";

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

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

type DecisionLike = {
  id?: number | string;
  status?: string;
  statusCode?: string;
};

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

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

function isDraftDecision(decision: DecisionLike): boolean {
  if (!hasValidDecisionId(decision)) {
    return false;
  }

  const status = String(decision.status ?? "")
    .trim()
    .toLowerCase();

  const statusCode = String(decision.statusCode ?? "")
    .trim()
    .toUpperCase();

  return status === "draft" || statusCode === "DRAFT";
}

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

  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 submittableDecisions = (plenary.rgcDecisions ?? []).filter(
      (decision) => hasValidDecisionId(decision as DecisionLike),
    );

    if (submittableDecisions.length === 0) {
      setSubmitDialogOpen(false);
      setFeedback({
        severity: "error",
        message: "No RGC Decision to submit to CDC.",
      });
      return;
    }

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

      await Promise.all(
        submittableDecisions.map((decision) =>
          submitRgcDecisionNotificationToCdc(Number(decision.id)),
        ),
      );

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

      await refetch();

      setFeedback({
        severity: "success",
        message: "RGC Decision submitted to CDC G-PSF successfully.",
      });
    } catch (submitError: unknown) {
      setFeedback({
        severity: "error",
        message: getErrorMessage(
          submitError,
          "Unable to submit RGC Decision to CDC.",
        ),
      });
    } finally {
      setIsSubmittingToCdc(false);
    }
  }

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

    try {
      setIsRgcSubmitting(true);

      if (!plenaryId || Number.isNaN(plenaryId)) {
        throw new Error("Invalid plenary ID.");
      }

      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("Please select category.");
      }

      if (!indicatorId) {
        throw new Error("Please select indicator.");
      }

      if (!meetingDate) {
        throw new Error("Please select meeting date.");
      }

      if (!focalPerson) {
        throw new Error("Please enter focal person.");
      }

      if (!decision) {
        throw new Error("Please enter RGC Decision.");
      }

      if (!verificationSource) {
        throw new Error("Please enter Source of Verification.");
      }

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

      await refetch();

      closeCreateRgcDecisionDialog();

      setFeedback({
        severity: "success",
        message: "RGC Decision saved successfully.",
      });
    } catch (saveError: unknown) {
      setFeedback({
        severity: "error",
        message: getErrorMessage(
          saveError,
          "Unable to save RGC Decision.",
        ),
      });
    } finally {
      setIsRgcSubmitting(false);
    }
  }

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

    try {
      setIsRgcSubmitting(true);

      if (!plenaryId || Number.isNaN(plenaryId)) {
        throw new Error("Invalid plenary ID.");
      }

      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("Please select category.");
      }

      if (!indicatorId) {
        throw new Error("Please select indicator.");
      }

      if (!meetingDate) {
        throw new Error("Please select meeting date.");
      }

      if (!focalPerson) {
        throw new Error("Please enter focal person.");
      }

      if (!decision) {
        throw new Error("Please enter RGC Decision.");
      }

      if (!verificationSource) {
        throw new Error("Please enter Source of Verification.");
      }
      
      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("Created RGC Decision ID was not returned from API.");
      }

      await submitRgcDecisionNotificationToCdc(rgcDecisionId);

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

      await refetch();

      closeCreateRgcDecisionDialog();

      setFeedback({
        severity: "success",
        message: "RGC Decision sent to CDC G-PSF successfully.",
      });
    } catch (sendError: unknown) {
      setFeedback({
        severity: "error",
        message: getErrorMessage(
          sendError,
          "Unable to send RGC Decision to CDC.",
        ),
      });
    } 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 }}>
            Plenary record not found
          </Typography>

          <Typography color="text.secondary" sx={{ mt: 1 }}>
            {error || "The selected plenary does not exist."}
          </Typography>

          <Button
            variant="contained"
            onClick={() => router.push("/ministry/plenary/plenaries")}
            sx={{
              mt: 3,
              textTransform: "none",
            }}
          >
            Back to All Plenaries
          </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,
                }}
              >
                Plenary Detail
              </Typography>

              <Typography
                variant="body2"
                color="text.secondary"
                sx={{ mt: 0.45 }}
              >
                Detail information of plenary report.
              </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",
                },
              }}
            >
              Submit to CDC
            </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",
                },
              }}
            >
              Create RGC Decision
            </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="Deadline :"
                value={plenary.deadline || "-"}
              />

              <DetailItem
                icon={<ScheduleOutlinedIcon fontSize="small" />}
                label="Meeting Date :"
                value={plenary.meetingDate || "-"}
              />

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

            <Stack spacing={3.25}>
              <DetailItem
                icon={<ChatBubbleOutlineRoundedIcon fontSize="small" />}
                label="Number of RGC Decision :"
                value={rgcDecisions.length}
              />

              <DetailItem
                icon={<InsertDriveFileOutlinedIcon fontSize="small" />}
                label="Attachment :"
                value={
                  <Stack
                    direction="row"
                    spacing={1}
                    sx={{
                      minWidth: 0,
                      alignItems: "center",
                    }}
                  >
                    <PictureAsPdfOutlinedIcon
                      sx={{
                        flexShrink: 0,
                        color: "#EF4444",
                        fontSize: 20,
                      }}
                    />

                    <Box sx={{ minWidth: 0 }}>
                      <Typography
                        variant="body2"
                        title={plenary.documentName}
                        sx={{
                          overflow: "hidden",
                          fontWeight: 700,
                          whiteSpace: "nowrap",
                          textOverflow: "ellipsis",
                        }}
                      >
                        {plenary.documentName || "Plenary Document"}
                      </Typography>

                      <Typography variant="caption" color="text.secondary">
                        {plenary.documentSize || "-"}
                      </Typography>
                    </Box>
                  </Stack>
                }
              />
            </Stack>
          </Box>
        </Box>

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

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

        <DialogContent
          sx={{
            pt: "12px !important",
            textAlign: "center",
          }}
        >
          <Typography variant="body2" color="text.secondary">
            Submit RGC Decisions to CDC G-PSF?
          </Typography>
        </DialogContent>

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

          <Button
            fullWidth
            variant="contained"
            disabled={isSubmittingToCdc}
            onClick={() => void handleSubmitToCdc()}
            sx={{ textTransform: "none" }}
          >
            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
              ? "Saving RGC Decision"
              : "Submitting RGC Decision to CDC"
          }
        />
      ) : null}
    </>
  );
}

export default PlenaryDetailScreen;