"use client";

import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { alpha, keyframes, useTheme } 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 { ExportIconButton } from "@/features/ministry/dashboard/components/charts/export-icon-button";
import { categoryRows } from "@/features/ministry/dashboard/dashboard-data";

const growX = keyframes`
  from {
    transform: scaleX(0);
  }
  to {
    transform: scaleX(1);
  }
`;

const fadeInText = keyframes`
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
`;

// One bar of the category chart.
export type CategoryIssueRow = {
  label: string;
  value: number;
};

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

type CategoryBarProps = {
  label: string;
  value: number;
  index: number;
  axisMax: number;
};

function CategoryBar({ label, value, index, axisMax }: CategoryBarProps) {
  const theme = useTheme();
  const delay = index * 0.06;
  const widthPercent = `${(value / axisMax) * 100}%`;

  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: { xs: "1fr", md: "120px minmax(0, 1fr)" },
        alignItems: "center",
        gap: 1.5,
      }}
    >
      <Typography sx={{ color: theme.palette.text.primary, fontSize: 12 }}>
        {label}
      </Typography>

      <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
        <Box
          sx={{
            width: "100%",
            height: 20,
            bgcolor:
              theme.palette.mode === "dark"
                ? alpha(theme.palette.common.white, 0.08)
                : "#edf2f7",
            borderRadius: "4px",
            overflow: "hidden",
          }}
        >
          <Box
            sx={{
              width: widthPercent,
              minWidth: value > 0 ? 22 : 0,
              height: "100%",
              position: "relative",
              overflow: "hidden",
            }}
          >
            <Box
              sx={{
                position: "absolute",
                inset: 0,
                bgcolor:
                  theme.palette.mode === "dark"
                    ? alpha(theme.palette.primary.main, 0.8)
                    : "#173f67",
                transform: value > 0 ? "scaleX(0)" : "none",
                transformOrigin: "left center",
                animation: value > 0 ? `${growX} 0.55s ease forwards` : undefined,
                animationDelay: `${delay}s`,
              }}
            />

            <Box
              sx={{
                position: "relative",
                zIndex: 1,
                width: "100%",
                height: "100%",
                color: "#ffffff",
                display: "flex",
                alignItems: "center",
                justifyContent: "flex-end",
                px: 1,
                fontSize: 10,
                fontWeight: 600,
                opacity: value > 0 ? 0 : 1,
                animation: value > 0 ? `${fadeInText} 0.2s ease forwards` : undefined,
                animationDelay: `${delay + 0.25}s`,
              }}
            >
              {value > 0 ? value : ""}
            </Box>
          </Box>
        </Box>
      </Box>
    </Box>
  );
}

export function CategoryIssuesCard({
  rows = categoryRows,
  onExport,
}: CategoryIssuesCardProps) {
  const theme = useTheme();

  // The scale used to be fixed at 6 (mock data never went higher). With real
  // data we round the biggest value up to the next multiple of 3 so the four
  // footer numbers (0, 1/3, 2/3, max) are always whole numbers. The minimum
  // stays 6 so the mock renders exactly like before (0 2 4 6).
  const highestValue = Math.max(0, ...rows.map((row) => row.value));
  const axisMax = Math.max(6, Math.ceil(highestValue / 3) * 3);
  const axisTicks = [0, axisMax / 3, (axisMax / 3) * 2, axisMax];

  return (
    <DashboardCard
      title="Category of Issues"
      action={<ExportIconButton onExport={onExport} />}
    >
      <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
        {rows.map((row, index) => (
          <CategoryBar
            key={row.label}
            label={row.label}
            value={row.value}
            index={index}
            axisMax={axisMax}
          />
        ))}
      </Box>

      <Box
        sx={{
          mt: 2,
          display: "flex",
          justifyContent: "space-between",
          pl: { xs: 0, md: "124px" },
          color: theme.palette.text.secondary,
          fontSize: 11,
        }}
      >
        {axisTicks.map((tick) => (
          <span key={tick}>{tick}</span>
        ))}
      </Box>
    </DashboardCard>
  );
}