"use client";

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

import {
  Bar,
  BarChart,
  LabelList,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

import {
  agencyRows,
  IN_PROGRESS_COLOR,
} from "../../plenary-data";

import { ChartExportMenuButton } from "./chart-export-menu-button";
import { PlenaryChartCard } from "./plenary-chart-card";
import { PlenaryLegend } from "./plenary-legend";
import { usePlenaryChartReady } from "./use-plenary-chart-ready";

type AgencyTooltipProps = {
  active?: boolean;
  payload?: Array<{
    payload?: {
      solved?: number;
      inProgress?: number;
    };
  }>;
  label?: string;
};

function AgencyTooltip({
  active,
  payload,
  label,
}: AgencyTooltipProps) {
  const theme = useTheme();

  if (!active || !payload?.length) {
    return null;
  }

  const row = payload[0]?.payload;

  return (
    <Box
      sx={{
        borderRadius: "12px",
        border: `1px solid ${theme.palette.divider}`,
        bgcolor: theme.palette.background.paper,
        px: 1.5,
        py: 1,
        boxShadow:
          theme.palette.mode === "dark"
            ? "0 8px 24px rgba(0, 0, 0, 0.45)"
            : "0 8px 24px rgba(15, 23, 42, 0.12)",
      }}
    >
      <Typography
        sx={{
          mb: 0.5,
          color: theme.palette.text.primary,
          fontSize: 12,
          fontWeight: 600,
        }}
      >
        {label}
      </Typography>

      <Typography
        sx={{
          color: theme.palette.success.main,
          fontSize: 12,
        }}
      >
        Solved: {row?.solved ?? 0}
      </Typography>

      <Typography
        sx={{
          color: IN_PROGRESS_COLOR,
          fontSize: 12,
        }}
      >
        In Progress: {row?.inProgress ?? 0}
      </Typography>
    </Box>
  );
}

function AgencyStatusChart() {
  const chartReady = usePlenaryChartReady();
  const theme = useTheme();

  if (!chartReady) {
    return <Box sx={{ height: 250 }} />;
  }

  return (
    <ResponsiveContainer
      width="100%"
      height={250}
      minWidth={0}
    >
      <BarChart
        data={agencyRows}
        barCategoryGap="20%"
        margin={{
          top: 6,
          right: 6,
          left: 6,
          bottom: 44,
        }}
      >
        <XAxis
          dataKey="name"
          interval={0}
          angle={-65}
          textAnchor="end"
          height={60}
          tick={{
            fontSize: 10,
            fill: theme.palette.text.secondary,
          }}
          axisLine={false}
          tickLine={false}
        />

        <YAxis hide domain={[0, 1]} />

        <Tooltip content={<AgencyTooltip />} />

        <Bar
          dataKey="solvedDisplay"
          stackId="status"
          fill={theme.palette.success.main}
          radius={[2, 2, 2, 2]}
          barSize={22}
          isAnimationActive={false}
        >
          <LabelList
            dataKey="solved"
            position="insideTop"
            fill="#ffffff"
            fontSize={9}
            formatter={(value: unknown) =>
              typeof value === "number" && value > 0
                ? String(value)
                : ""
            }
          />
        </Bar>

        <Bar
          dataKey="inProgressDisplay"
          stackId="status"
          fill={IN_PROGRESS_COLOR}
          radius={[2, 2, 2, 2]}
          barSize={22}
          isAnimationActive={false}
        >
          <LabelList
            dataKey="inProgress"
            position="insideTop"
            fill="#ffffff"
            fontSize={9}
            formatter={(value: unknown) =>
              typeof value === "number" && value > 0
                ? String(value)
                : ""
            }
          />
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}

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

  return (
    <PlenaryChartCard>
      <Box
        sx={{
          mb: 2,
          display: "grid",
          gridTemplateColumns: "24px 1fr 34px",
          alignItems: "center",
          gap: 1,
        }}
      >
        <Box />

        <Typography
          sx={{
            color: theme.palette.text.secondary,
            fontSize: 12,
            fontWeight: 600,
            textAlign: "center",
          }}
        >
          Government Primary Agencies
        </Typography>

        <Box
          sx={{
            display: "flex",
            justifyContent: "flex-end",
          }}
        >
          <ChartExportMenuButton />
        </Box>
      </Box>

      <AgencyStatusChart />

      <PlenaryLegend
        items={[
          {
            label: "Solved",
            color: theme.palette.success.main,
          },
          {
            label: "In Progress",
            color: IN_PROGRESS_COLOR,
          },
        ]}
      />
    </PlenaryChartCard>
  );
}