import React, { useMemo } from 'react';
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { useTheme } from '@/app/providers/ThemeProvider';
import { useLocale } from '@/app/providers/LocaleProvider';
import { ChartResponsiveContainer } from '@/features/dashboard/components/ChartResponsiveContainer';
import {
  CategoryAxisTick,
  ChartShell,
  createChartTooltipRenderer,
  estimateCategoryAxisWidth,
  getChartAnimationProps,
  getChartAxisTick,
  getChartGridProps,
  getChartMargin,
} from '@/features/dashboard/components/charts';
import { getChartPalette } from '@/features/dashboard/utils/chartColors';
import type { ChartDataset } from '@/features/dashboard/types/dashboard.types';

interface HorizontalBarChartProps {
  title: string;
  dataset: ChartDataset;
  emptyLabel: string;
  emptyHint?: string;
  labelMap?: Record<string, string>;
}

export const HorizontalBarChart: React.FC<HorizontalBarChartProps> = ({
  title,
  dataset,
  emptyLabel,
  emptyHint,
  labelMap = {},
}) => {
  const { theme } = useTheme();
  const { locale } = useLocale();
  const palette = getChartPalette(theme);
  const numberFormat = new Intl.NumberFormat(locale);

  const chartData = useMemo(
    () =>
      dataset.labels.map((label, index) => ({
        name: labelMap[label] ?? label,
        value: dataset.data[index] ?? 0,
      })),
    [dataset, labelMap],
  );

  const hasData = chartData.some((item) => item.value > 0);
  const categoryLabels = chartData.map((item) => item.name);
  const yAxisWidth = estimateCategoryAxisWidth(categoryLabels);
  const barCategoryGap = chartData.length <= 2 ? '35%' : chartData.length <= 4 ? '22%' : '14%';

  const tooltipRenderer = createChartTooltipRenderer(undefined, (_name, value) => ({
    name: title,
    value: numberFormat.format(value),
  }));

  return (
    <ChartShell
      title={title}
      empty={!hasData}
      emptyLabel={emptyLabel}
      emptyHint={emptyHint}
      fill
    >
      <ChartResponsiveContainer fill>
        {({ width, height }) => (
          <BarChart
            width={width}
            height={height}
            data={chartData}
            layout="vertical"
            margin={getChartMargin('compact')}
            barCategoryGap={barCategoryGap}
          >
            <CartesianGrid {...getChartGridProps(theme)} horizontal={false} />
            <XAxis
              type="number"
              allowDecimals={false}
              tick={getChartAxisTick(theme, 'middle')}
              axisLine={false}
              tickLine={false}
              tickMargin={6}
            />
            <YAxis
              type="category"
              dataKey="name"
              width={yAxisWidth}
              tick={(props) => <CategoryAxisTick {...props} theme={theme} />}
              axisLine={false}
              tickLine={false}
              tickMargin={8}
              interval={0}
            />
            <Tooltip content={tooltipRenderer} cursor={{ fill: theme.colors.primary, opacity: 0.06 }} />
            <Bar dataKey="value" radius={[0, 4, 4, 0]} maxBarSize={24} {...getChartAnimationProps()}>
              {chartData.map((entry, index) => (
                <Cell key={entry.name} fill={palette[index % palette.length]} />
              ))}
            </Bar>
          </BarChart>
        )}
      </ChartResponsiveContainer>
    </ChartShell>
  );
};
