"use client";

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

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 { DashboardStackedBarRow } from "@/features/ministry/dashboard/components/charts/dashboard-stacked-bar-row";
import { ExportIconButton } from "@/features/ministry/dashboard/components/charts/export-icon-button";
import {
  IN_PROGRESS_COLOR,
  NOT_ADDRESSED_COLOR,
  SOLVED_COLOR,
  workingGroupRows,
} from "@/features/ministry/dashboard/dashboard-data";

const fadeUp = keyframes`
  from {
    opacity: 0;
    transform: translateY(8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

// One stacked bar of the working group chart. Raw counts are fine here:
// DashboardStackedBarRow divides each segment by the row total itself.
export type WorkingGroupStatusRow = {
  label: string;
  solved: number;
  inProgress: number;
  notAddressed: number;
};

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

export function WorkingGroupStatusCard({
  rows = workingGroupRows,
  onExport,
}: WorkingGroupStatusCardProps) {
  return (
    <DashboardCard
      title="Working Group"
      action={<ExportIconButton onExport={onExport} />}
    >
      <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
        {rows.map((row, index) => (
          <Box
            key={row.label}
            sx={{
              opacity: 0,
              animation: `${fadeUp} 0.35s ease forwards`,
              animationDelay: `${index * 0.045}s`,
            }}
          >
            <DashboardStackedBarRow
              label={row.label}
              segments={[
                { value: row.solved, color: SOLVED_COLOR, label: row.solved },
                {
                  value: row.inProgress,
                  color: IN_PROGRESS_COLOR,
                  label: row.inProgress,
                },
                {
                  value: row.notAddressed,
                  color: NOT_ADDRESSED_COLOR,
                  label: row.notAddressed,
                },
              ]}
              labelWidth={190}
              rowHeight={14}
              labelFontSize={10}
            />
          </Box>
        ))}
      </Box>

      <DashboardLegend
        items={[
          { label: "Solved", color: SOLVED_COLOR },
          { label: "In Progress", color: IN_PROGRESS_COLOR },
          { label: "Not Addressed", color: NOT_ADDRESSED_COLOR },
        ]}
      />
    </DashboardCard>
  );
}