"use client";

import { useMemo, useState } from "react";

import ArticleOutlinedIcon from "@mui/icons-material/ArticleOutlined";
import AssignmentTurnedInOutlinedIcon from "@mui/icons-material/AssignmentTurnedInOutlined";
import BusinessOutlinedIcon from "@mui/icons-material/BusinessOutlined";
import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined";
import PendingActionsOutlinedIcon from "@mui/icons-material/PendingActionsOutlined";
import ReportProblemOutlinedIcon from "@mui/icons-material/ReportProblemOutlined";

import {
  Alert,
  Box,
  Button,
  Paper,
  Stack,
  Typography,
} from "@mui/material";
import { alpha, useTheme } from "@mui/material/styles";

import type { RgcDecisionRow } from "../rgc-decision-data";
import { useRgcDecisions } from "../hook/use-rgc-decisions";

import { RgcDecisionDetailScreen } from "../view-detail/rgc-decision-detail-screen";
import { RgcDecisionFilters } from "./rgc-decision-filters";
import { RgcDecisionTable } from "./rgc-decision-table";

type SummaryTone = "blue" | "green" | "yellow" | "red" | "gray";

type SummaryCardProps = {
  label: string;
  value: string;
  icon: React.ReactNode;
  tone: SummaryTone;
};

const CARD_TONES: Record<
  SummaryTone,
  {
    background: string;
    border: string;
    icon: string;
  }
> = {
  blue: {
    background: "#EAF4FF",
    border: "#A8D5FF",
    icon: "#168CE6",
  },
  green: {
    background: "#ECFDF3",
    border: "#BBF7D0",
    icon: "#22C55E",
  },
  yellow: {
    background: "#FFF9E8",
    border: "#FDE68A",
    icon: "#F59E0B",
  },
  red: {
    background: "#FEF2F2",
    border: "#FECACA",
    icon: "#EF4444",
  },
  gray: {
    background: "#F3F4F6",
    border: "#D1D5DB",
    icon: "#6B7280",
  },
};

function SummaryCard({
  label,
  value,
  icon,
  tone,
}: SummaryCardProps) {
  const theme = useTheme();
  const colors = CARD_TONES[tone];
  const isDark = theme.palette.mode === "dark";

  return (
    <Paper
      elevation={0}
      sx={{
        minWidth: 0,
        minHeight: 98,
        px: 2,
        py: 1.7,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 1.5,
        borderRadius: "12px",
        border: `1px solid ${colors.border}`,
        bgcolor: isDark
          ? alpha(colors.icon, 0.1)
          : colors.background,
      }}
    >
      <Box sx={{ minWidth: 0 }}>
        <Typography
          sx={{
            mb: 0.35,
            color: theme.palette.text.secondary,
            fontSize: 12,
            fontWeight: 500,
          }}
        >
          {label}
        </Typography>

        <Typography
          sx={{
            color: theme.palette.text.primary,
            fontSize: 26,
            fontWeight: 800,
            lineHeight: 1.15,
            whiteSpace: "nowrap",
          }}
        >
          {value}
        </Typography>
      </Box>

      <Box
        sx={{
          width: 46,
          height: 46,
          display: "grid",
          placeItems: "center",
          flexShrink: 0,
          borderRadius: "10px",
          bgcolor: theme.palette.background.paper,
          color: colors.icon,
          border: `1px solid ${alpha(colors.icon, 0.2)}`,
        }}
      >
        {icon}
      </Box>
    </Paper>
  );
}

export function IssueMatrixRgcDecisionScreen() {
  const theme = useTheme();

  const [activeTab, setActiveTab] =
    useState<"issueMatrix" | "rgcDecision">("rgcDecision");
  const [selectedDecision, setSelectedDecision] =
    useState<RgcDecisionRow | null>(null);

  const {
    rows,
    filteredRows,
    ministries,
    categories,
    loading,
    error,

    selectedStatuses,
    selectedPrimaryAgencyIds,
    selectedCategoryIds,
    meetingDate,

    toggleStatus,
    togglePrimaryAgency,
    toggleCategory,
    setMeetingDate,
    resetFilters,

    reload,
  } = useRgcDecisions();

  const summary = useMemo(() => {
    const total = rows.length;
    const solved = rows.filter(
      (row) => row.status === "Solved",
    ).length;
    const inProgress = rows.filter(
      (row) => row.status === "In Progress",
    ).length;
    const notAddressed = rows.filter(
      (row) => row.status === "Not Addressed",
    ).length;

    const totalAgencies = new Set(
      rows
        .map((row) => row.stakeholderId)
        .filter(
          (id) =>
            Number.isInteger(id) &&
            id > 0,
        ),
    ).size;

    return {
      total,
      solved,
      inProgress,
      notAddressed,
      totalAgencies,
    };
  }, [rows]);

  if (selectedDecision) {
    return (
      <RgcDecisionDetailScreen
        row={selectedDecision}
        onBack={() => setSelectedDecision(null)}
      />
    );
  }

  return (
    <Box
      sx={{
        width: "100%",
        maxWidth: "100%",
        minHeight: "calc(100vh - 64px)",
        px: {
          xs: 2,
          md: 3,
        },
        py: 2.5,
        bgcolor: theme.palette.background.default,
        color: theme.palette.text.primary,
        overflowX: "hidden",
      }}
    >
      <Stack
        direction={{
          xs: "column",
          lg: "row",
        }}
        spacing={2}
        sx={{
          mb: 2.5,
          alignItems: {
            xs: "stretch",
            lg: "flex-start",
          },
          justifyContent: "space-between",
        }}
      >
        <Box>
          <Typography
            sx={{
              color: theme.palette.text.primary,
              fontSize: {
                xs: 28,
                md: 34,
              },
              fontWeight: 800,
              letterSpacing: "-0.03em",
              lineHeight: 1.1,
            }}
          >
            RGC Decision
          </Typography>

          <Typography
            sx={{
              mt: 1,
              color: theme.palette.text.secondary,
              fontSize: 12,
              fontWeight: 500,
            }}
          >
            Issues Matrix and RGC Decision /{" "}
            <Box
              component="span"
              sx={{
                color: theme.palette.text.primary,
                fontWeight: 700,
              }}
            >
              RGC Decision
            </Box>
          </Typography>
        </Box>

        <Stack
          direction="row"
          spacing={1.5}
          sx={{
            alignItems: "center",
            justifyContent: {
              xs: "flex-start",
              lg: "flex-end",
            },
          }}
        >
          <Button
            variant={
              activeTab === "issueMatrix"
                ? "contained"
                : "outlined"
            }
            startIcon={
              <ArticleOutlinedIcon
                sx={{ fontSize: 18 }}
              />
            }
            onClick={() =>
              setActiveTab("issueMatrix")
            }
            sx={{
              minWidth: 145,
              height: 42,
              borderRadius: "6px",
              textTransform: "none",
              fontSize: 13,
              fontWeight: 700,
              boxShadow: "none",
            }}
          >
            Issue Matrix
          </Button>

          <Button
            variant={
              activeTab === "rgcDecision"
                ? "contained"
                : "outlined"
            }
            startIcon={
              <AssignmentTurnedInOutlinedIcon
                sx={{ fontSize: 18 }}
              />
            }
            onClick={() =>
              setActiveTab("rgcDecision")
            }
            sx={{
              minWidth: 155,
              height: 42,
              borderRadius: "6px",
              textTransform: "none",
              fontSize: 13,
              fontWeight: 700,
              boxShadow: "none",
            }}
          >
            RGC Decision
          </Button>
        </Stack>
      </Stack>

      {error ? (
        <Alert
          severity="error"
          sx={{ mb: 2 }}
          action={
            <Button
              color="inherit"
              size="small"
              onClick={() =>
                void reload()
              }
            >
              Reload
            </Button>
          }
        >
          {error}
        </Alert>
      ) : null}

      {activeTab === "issueMatrix" ? (
        <Paper
          elevation={0}
          sx={{
            p: 4,
            textAlign: "center",
            borderRadius: "12px",
            border: `1px solid ${theme.palette.divider}`,
            bgcolor: theme.palette.background.paper,
          }}
        >
          <ArticleOutlinedIcon
            sx={{
              mb: 1,
              fontSize: 42,
              color: theme.palette.text.secondary,
            }}
          />

          <Typography
            sx={{
              fontSize: 18,
              fontWeight: 800,
            }}
          >
            Issue Matrix
          </Typography>

          <Typography
            sx={{
              mt: 0.75,
              color: theme.palette.text.secondary,
              fontSize: 13,
            }}
          >
            Connect your Issue Matrix component here.
          </Typography>
        </Paper>
      ) : (
        <>
          <RgcDecisionFilters
            ministries={ministries}
            categories={categories}
            selectedStatuses={selectedStatuses}
            selectedPrimaryAgencyIds={
              selectedPrimaryAgencyIds
            }
            selectedCategoryIds={
              selectedCategoryIds
            }
            meetingDate={meetingDate}
            onToggleStatus={toggleStatus}
            onTogglePrimaryAgency={
              togglePrimaryAgency
            }
            onToggleCategory={toggleCategory}
            onMeetingDateChange={
              setMeetingDate
            }
            onReset={resetFilters}
          />

          <Box
            sx={{
              mb: 2.5,
              display: "grid",
              gridTemplateColumns: {
                xs: "1fr",
                sm: "repeat(2, minmax(0, 1fr))",
                lg: "repeat(5, minmax(0, 1fr))",
              },
              gap: 2,
            }}
          >
            <SummaryCard
              label="Total Issues"
              value={String(summary.total)}
              tone="blue"
              icon={
                <DescriptionOutlinedIcon />
              }
            />

            <SummaryCard
              label="Solved"
              value={`${summary.solved}/${summary.total}`}
              tone="green"
              icon={
                <AssignmentTurnedInOutlinedIcon />
              }
            />

            <SummaryCard
              label="In Progress"
              value={`${summary.inProgress}/${summary.total}`}
              tone="yellow"
              icon={
                <PendingActionsOutlinedIcon />
              }
            />

            <SummaryCard
              label="Not Addressed"
              value={`${summary.notAddressed}/${summary.total}`}
              tone="red"
              icon={
                <ReportProblemOutlinedIcon />
              }
            />

            <SummaryCard
              label="Total Primary Agencies"
              value={`${summary.totalAgencies}/${
                ministries.length ||
                summary.totalAgencies
              }`}
              tone="gray"
              icon={
                <BusinessOutlinedIcon />
              }
            />
          </Box>

          <Stack
            direction="row"
            sx={{
              mb: 1.5,
              alignItems: "center",
              justifyContent: "space-between",
              gap: 2,
            }}
          >
            <Typography
              sx={{
                color: theme.palette.text.primary,
                fontSize: 16,
                fontWeight: 800,
              }}
            >
              List of RGC Decisions
            </Typography>


          </Stack>

          <RgcDecisionTable
            rows={filteredRows}
            loading={loading}
            onViewDetail={(row) =>
              setSelectedDecision(row)
            }
          />
        </>
      )}


    </Box>
  );
}

export default IssueMatrixRgcDecisionScreen;