"use client";

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

import ArrowBackIosNewIcon from "@mui/icons-material/ArrowBackIosNew";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Typography from "@mui/material/Typography";

import { PlenaryMinistryTable } from "../components/plenary-ministry-table";
import type { PlenaryApiItem } from "../plenary-data";
import { getPlenaryDetail } from "../service/plenary-service";
import { PlenaryDetailInfo } from "./plenary-detail-info";
import { PlenaryRgcDecisionTable } from "./plenary-rgc-decision-table";

type DetailState = {
  loadedId: number;
  plenary: PlenaryApiItem | null;
  error: string | null;
};

export function PlenaryDetailScreen() {
  const router = useRouter();

  const params = useParams<{
    id?: string | string[];
  }>();

  const routeId = Array.isArray(params?.id)
    ? params.id[0]
    : params?.id;

  const id = Number(routeId);

  const isValidId = Number.isInteger(id) && id > 0;

  const [detailState, setDetailState] = useState<DetailState>({
    loadedId: 0,
    plenary: null,
    error: null,
  });

  const loading =
    isValidId && detailState.loadedId !== id;

  useEffect(() => {
    if (!isValidId) {
      return;
    }

    let cancelled = false;

    async function loadDetail() {
      try {
        const data = await getPlenaryDetail(id);

        if (cancelled) {
          return;
        }

        setDetailState({
          loadedId: id,
          plenary: data,
          error: null,
        });
      } catch (error) {
        if (cancelled) {
          return;
        }

        setDetailState({
          loadedId: id,
          plenary: null,
          error:
            error instanceof Error
              ? error.message
              : "Unable to load plenary detail.",
        });
      }
    }

    void loadDetail();

    return () => {
      cancelled = true;
    };
  }, [id, isValidId]);

  const errorMessage = !isValidId
    ? "Invalid Plenary ID."
    : detailState.loadedId === id
      ? detailState.error
      : null;

  const plenary =
    detailState.loadedId === id
      ? detailState.plenary
      : null;

  return (
    <Box
      sx={{
        minHeight: "100vh",
        p: {
          xs: 2,
          sm: 3,
          md: 4,
        },
        bgcolor: "background.default",
        color: "text.primary",
      }}
    >
      {/* Back + title use flex row */}
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: {
            xs: 1.25,
            sm: 2,
          },
          mb: {
            xs: 4,
            md: 5,
          },
        }}
      >
        <Button
          startIcon={
            <ArrowBackIosNewIcon
              sx={{
                fontSize: 15,
              }}
            />
          }
          onClick={() => router.back()}
          sx={{
            minWidth: "auto",
            px: 0.5,
            py: 0.5,
            flexShrink: 0,
            color: "text.secondary",
            fontSize: 14,
            fontWeight: 500,
            textTransform: "none",

            "&:hover": {
              bgcolor: "transparent",
              color: "primary.main",
            },
          }}
        >
          Back
        </Button>

        <Box
          sx={{
            minWidth: 0,
          }}
        >
          <Typography
            sx={{
              fontSize: {
                xs: 20,
                md: 22,
              },
              lineHeight: 1.3,
              fontWeight: 700,
            }}
          >
            Plenary Detail
          </Typography>

          <Typography
            sx={{
              mt: 0.25,
              color: "text.secondary",
              fontSize: {
                xs: 12,
                md: 13,
              },
            }}
          >
            Detail Information of Plenary Report
          </Typography>
        </Box>
      </Box>

      {loading ? (
        <Box
          sx={{
            minHeight: 300,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <CircularProgress />
        </Box>
      ) : null}

      {!loading && errorMessage ? (
        <Typography
          sx={{
            color: "error.main",
            fontSize: 14,
            fontWeight: 600,
          }}
        >
          {errorMessage}
        </Typography>
      ) : null}

      {!loading && !errorMessage && !plenary ? (
        <Typography
          sx={{
            color: "text.secondary",
            fontSize: 14,
          }}
        >
          No data
        </Typography>
      ) : null}

      {!loading && plenary ? (
        <Box>
          <PlenaryDetailInfo plenary={plenary} />

          <Box sx={{ mt: 3 }}>
            <Typography
              sx={{
                mb: 1.5,
                fontSize: 16,
                fontWeight: 700,
              }}
            >
              List of Ministry
            </Typography>

            <PlenaryMinistryTable
              plenaryId={plenary.id}
              ministries={plenary.ministries ?? []}
            />
          </Box>

          <PlenaryRgcDecisionTable plenaryId={plenary.id} />
        </Box>
      ) : null}
    </Box>
  );
}

export default PlenaryDetailScreen;