"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 type { ChartExportFormat } from "@/components/ui/chart-export-menu-button";
import { DashboardCard } from "@/features/ministry/dashboard/components/charts/dashboard-card";
import { DashboardLegend } from "@/features/ministry/dashboard/components/charts/dashboard-legend";
import { useDashboardChartReady } from "@/features/ministry/dashboard/components/charts/use-dashboard-chart-ready";
import { ExportIconButton } from "@/features/ministry/dashboard/components/charts/export-icon-button";
import {
  agencyRows,
  IN_PROGRESS_COLOR,
  NOT_ADDRESSED_COLOR,
  SOLVED_COLOR,
} from "@/features/ministry/dashboard/dashboard-data";

// One bar of the agency chart. `solved`/`inProgress`/`notAddressed` are the
// raw counts shown in labels and the tooltip; the *Display fields are 0..1
// fractions that drive the bar heights (the Y axis is fixed to [0, 1]).
// The notAddressed fields are optional so older data (like the design mock)
// keeps working — rows without them simply show no red segment.
export type AgencyStatusRow = {
  name: string;
  solved: number;
  inProgress: number;
  solvedDisplay: number;
  inProgressDisplay: number;
  notAddressed?: number;
  notAddressedDisplay?: number;
};

type AgencyStatusCardProps = {
  // Defaults to the design mock so screens that render this card without
  // props (e.g. the ministry dashboard) keep working.
  rows?: AgencyStatusRow[];
  // Called when the user picks CSV / XLSX / Image from the save icon.
  onExport?: (format: ChartExportFormat) => void;
};

type AgencyTooltipProps = {
  active?: boolean;
  payload?: Array<{
    payload: {
      solved: number;
      inProgress: number;
      notAddressed?: 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>

      {row.notAddressed !== undefined ? (
        <Typography sx={{ color: NOT_ADDRESSED_COLOR, fontSize: 12 }}>
          Not Addressed: {row.notAddressed}
        </Typography>
      ) : null}
    </Box>
  );
}

function AgencyStatusChart({ rows }: { rows: AgencyStatusRow[] }) {
  const { containerRef, chartReady } = useDashboardChartReady();
  const theme = useTheme();

  return (
    <Box ref={containerRef} sx={{ height: 210 }}>
      {chartReady ? (
        <ResponsiveContainer width="100%" height={210} minWidth={0}>
          <BarChart
            data={rows}
            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>

            {/* Rows without notAddressed data (like the design mock) simply
                render nothing for this segment. */}
            <Bar
              dataKey="notAddressedDisplay"
              stackId="status"
              fill={NOT_ADDRESSED_COLOR}
              radius={[2, 2, 2, 2]}
              barSize={22}
              isAnimationActive
              animationDuration={700}
              animationBegin={200}
            >
              <LabelList
                dataKey="notAddressed"
                position="insideTop"
                fill="#ffffff"
                fontSize={8}
                formatter={(value) =>
                  typeof value === "number" && value > 0 ? value : ""
                }
              />
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      ) : null}
    </Box>
  );
}

export function AgencyStatusCard({
  rows = agencyRows,
  onExport,
}: AgencyStatusCardProps) {
  // Only mention Not Addressed in the legend when the rows actually carry
  // that data — the design-mock rows do not, so the ministry dashboard
  // keeps its original two-item legend.
  const hasNotAddressedData = rows.some(
    (row) => row.notAddressed !== undefined,
  );

  const legendItems = [
    { label: "Solved", color: SOLVED_COLOR },
    { label: "In Progress", color: IN_PROGRESS_COLOR },
    ...(hasNotAddressedData
      ? [{ label: "Not Addressed", color: NOT_ADDRESSED_COLOR }]
      : []),
  ];

  return (
    <DashboardCard
      title="Government Primary Agencies"
      action={<ExportIconButton onExport={onExport} />}
    >
      <AgencyStatusChart rows={rows} />

      <DashboardLegend items={legendItems} />
    </DashboardCard>
  );
}