import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Paper, Stack, Text } from "@mantine/core";

import { overviewChartColors } from "./overview.styles";

export interface HorizontalBarItem {
  label: string;
  value: number;
}

interface OverviewHorizontalBarChartProps {
  title: string;
  data: HorizontalBarItem[];
  emptyMessage?: string;
  valueLabel?: string;
}

export function OverviewHorizontalBarChart({
  title,
  data,
  emptyMessage = "No data available",
  valueLabel = "Count",
}: OverviewHorizontalBarChartProps) {
  const chartData = data
    .filter((item) => item.value > 0)
    .map((item) => ({ name: item.label, value: item.value }));
  const hasData = chartData.length > 0;

  return (
    <Paper p="md" radius="lg" withBorder h="100%" style={{ minHeight: 240 }}>
      <Stack gap="sm" h="100%">
        <Text fw={600}>{title}</Text>
        {!hasData ? (
          <Text size="sm" c="dimmed" ta="center" py="xl">
            {emptyMessage}
          </Text>
        ) : (
          <ResponsiveContainer width="100%" height={Math.max(240, chartData.length * 36)}>
            <BarChart
              data={chartData}
              layout="vertical"
              margin={{ top: 4, right: 16, left: 8, bottom: 4 }}
            >
              <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" horizontal={false} />
              <XAxis type="number" allowDecimals={false} tick={{ fontSize: 12 }} />
              <YAxis
                type="category"
                dataKey="name"
                width={120}
                tick={{ fontSize: 11 }}
                stroke="#94a3b8"
              />
              <Tooltip formatter={(value) => [value, valueLabel]} />
              <Bar dataKey="value" radius={[0, 6, 6, 0]} barSize={18}>
                {chartData.map((entry, index) => (
                  <Cell
                    key={entry.name}
                    fill={
                      overviewChartColors.pipeline[
                        index % overviewChartColors.pipeline.length
                      ]
                    }
                  />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        )}
      </Stack>
    </Paper>
  );
}
