"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 { WorkingGroupChartCard } from "@/features/pswg/working-group/components/charts/working-group-chart-card";
import { WorkingGroupLegend } from "@/features/pswg/working-group/components/charts/working-group-legend";
import { useWorkingGroupChartReady } from "@/features/pswg/working-group/components/charts/use-working-group-chart-ready";
import { ExportIconButton } from "@/features/pswg/working-group/components/charts/export-icon-button";
import {
  agencyRows,
  IN_PROGRESS_COLOR,
  SOLVED_COLOR,
} from "@/features/pswg/working-group/working-group-data";

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: SOLVED_COLOR, fontSize: 12 }}>
        Solved: {row.solved}
      </Typography>

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

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

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

  return (
    <ResponsiveContainer width="100%" height={210} minWidth={0}>
      <BarChart
        data={agencyRows}
        margin={{ top: 0, right: 4, left: 4, bottom: 8 }}
        barCategoryGap="24%"
      >
        <XAxis
          dataKey="name"
          interval={0}
          angle={-68}
          textAnchor="end"
          height={58}
          tick={{ fontSize: 9, fill: theme.palette.text.secondary }}
          axisLine={false}
          tickLine={false}
        />
        <YAxis hide domain={[0, 1]} />
        <Tooltip content={<AgencyTooltip />} />
        <Bar
          dataKey="solvedDisplay"
          stackId="status"
          fill={SOLVED_COLOR}
          radius={[2, 2, 2, 2]}
          barSize={22}
          isAnimationActive
          animationDuration={700}
          animationBegin={80}
        >
          <LabelList
            dataKey="solved"
            position="insideTop"
            fill="#ffffff"
            fontSize={8}
            formatter={(value) =>
              typeof value === "number" && value > 0 ? value : ""
            }
          />
        </Bar>
        <Bar
          dataKey="inProgressDisplay"
          stackId="status"
          fill={IN_PROGRESS_COLOR}
          radius={[2, 2, 2, 2]}
          barSize={22}
          isAnimationActive
          animationDuration={700}
          animationBegin={140}
        >
          <LabelList
            dataKey="inProgress"
            position="insideTop"
            fill="#ffffff"
            fontSize={8}
            formatter={(value) =>
              typeof value === "number" && value > 0 ? value : ""
            }
          />
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}

export function AgencyStatusCard() {
  return (
    <WorkingGroupChartCard
      title="Government Primary Agencies"
      action={<ExportIconButton />}
    >
      <AgencyStatusChart />
      <WorkingGroupLegend
        items={[
          { label: "Solved", color: SOLVED_COLOR },
          { label: "In Progress", color: IN_PROGRESS_COLOR },
        ]}
      />
    </WorkingGroupChartCard>
  );
}
