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

import { BOOKING_LIST_TABS } from "@/features/bookings/booking-status.config";
import type { IOverviewPipelineCount } from "@/types/overview";
import { overviewChartColors } from "./overview.styles";

function getPipelineLabel(stage: string) {
  return BOOKING_LIST_TABS.find((tab) => tab.key === stage)?.label ?? stage;
}

export function OverviewStatusChart({ data }: { data: IOverviewPipelineCount[] }) {
  const chartData = data.map((item) => ({
    ...item,
    label: getPipelineLabel(item.stage),
  }));
  const hasData = chartData.some((item) => item.count > 0);

  return (
    <Paper p="lg" radius="lg" withBorder h="100%" style={{ minHeight: 320 }}>
      <Stack gap="md" h="100%">
        <Text fw={600}>Pipeline by stage</Text>
        {!hasData ? (
          <Text size="sm" c="dimmed" ta="center" py="xl">
            No bookings in pipeline
          </Text>
        ) : (
          <ResponsiveContainer width="100%" height={260}>
            <BarChart data={chartData} margin={{ top: 8, right: 8, left: 0, bottom: 24 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
              <XAxis
                dataKey="label"
                tick={{ fontSize: 11 }}
                interval={0}
                angle={-20}
                textAnchor="end"
                height={60}
                stroke="#94a3b8"
              />
              <YAxis allowDecimals={false} tick={{ fontSize: 12 }} stroke="#94a3b8" />
              <Tooltip formatter={(value) => [value, "Bookings"]} />
              <Bar dataKey="count" radius={[6, 6, 0, 0]}>
                {chartData.map((entry, index) => (
                  <Cell
                    key={entry.stage}
                    fill={
                      overviewChartColors.pipeline[
                        index % overviewChartColors.pipeline.length
                      ]
                    }
                  />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        )}
      </Stack>
    </Paper>
  );
}
