import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, Cell } from 'recharts';
import type { CanvasComponent } from '../../types/canvas';
import { RendererWrapper, GlassTooltip, NoDataPlaceholder, type ComponentRenderContext } from './RendererWrapper';

interface Props { component: CanvasComponent; ctx: ComponentRenderContext }

const PALETTE = ['#0EA5E9', '#22D3EE', '#3B82F6', '#8B5CF6', '#06B6D4', '#A78BFA'];

export function BarChartRenderer({ component, ctx }: Props) {
  const params = component.visualizationParameters as {
    xAxis?: string;
    yAxis?: string;
    sort?: 'asc' | 'desc';
    showLabels?: boolean;
    legend?: boolean;
    colorScale?: string[];
  };

  const rows = (component.dataRows ?? []) as Array<Record<string, number | string>>;
  const xKey = params.xAxis ?? component.dataBindings.dimensions[0] ?? 'category';
  const yKey = params.yAxis ?? component.dataBindings.measures[0] ?? 'value';
  const colors = params.colorScale ?? PALETTE;

  if (!rows.length) return (
    <RendererWrapper component={component} ctx={ctx}>
      <NoDataPlaceholder />
    </RendererWrapper>
  );

  const sorted = params.sort
    ? [...rows].sort((a, b) =>
        params.sort === 'desc'
          ? Number(b[yKey]) - Number(a[yKey])
          : Number(a[yKey]) - Number(b[yKey]),
      )
    : rows;

  return (
    <RendererWrapper component={component} ctx={ctx} minHeight={300}>
      <div className="h-[220px] w-full">
        <ResponsiveContainer width="100%" height="100%">
          <BarChart data={sorted} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
            <XAxis
              dataKey={xKey}
              stroke="#3f3f46"
              tick={{ fontSize: 11, fill: '#71717a' }}
              axisLine={false}
              tickLine={false}
              dy={6}
            />
            <YAxis
              stroke="#3f3f46"
              tick={{ fontSize: 11, fill: '#71717a' }}
              axisLine={false}
              tickLine={false}
            />
            <Tooltip content={<GlassTooltip />} cursor={{ fill: 'rgba(59,130,246,0.06)' }} />
            <Bar dataKey={yKey} radius={[6, 6, 0, 0]} maxBarSize={48}>
              {sorted.map((_, index) => (
                <Cell
                  key={`cell-${index}`}
                  fill={colors[index % colors.length]}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </RendererWrapper>
  );
}
