import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import type { IntelligenceGranularity, KpiTimeseriesPoint } from '@/infrastructure/http/api/intelligence';

type MetricKey = 'visits' | 'commands' | 'suggestedProducts' | 'revenueCents';

interface Props {
  points: KpiTimeseriesPoint[];
  granularity: IntelligenceGranularity;
  metricKey: MetricKey;
  seriesLabel: string;
  color: string;
  valueFormatter?: (n: number) => string;
}

function formatTick(period: string, granularity: IntelligenceGranularity): string {
  const d = new Date(period);
  if (Number.isNaN(d.getTime())) return period;
  switch (granularity) {
    case 'hour':  return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', hour12: false });
    case 'day':   return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
    case 'month': return d.toLocaleDateString(undefined, { month: 'short', year: 'numeric' });
    case 'year':  return d.getUTCFullYear().toString();
  }
}

export function KpiBarChart({ points, granularity, metricKey, seriesLabel, color, valueFormatter }: Props) {
  const data = points.map((p) => ({ period: formatTick(p.period, granularity), value: p[metricKey] }));
  const fmt = valueFormatter ?? ((n: number) => n.toLocaleString());
  return (
    <div className="w-full h-60">
      <ResponsiveContainer>
        <BarChart data={data} margin={{ top: 10, right: 20, left: 0, bottom: 0 }} barCategoryGap="20%">
          <CartesianGrid stroke="#e1e3e5" strokeDasharray="3 3" vertical={false} />
          <XAxis dataKey="period" stroke="#6d7175" tick={{ fontSize: 12 }} />
          <YAxis stroke="#6d7175" tick={{ fontSize: 12 }} allowDecimals={false} tickFormatter={fmt} />
          <Tooltip
            cursor={{ fill: 'rgba(0,0,0,0.04)' }}
            contentStyle={{ background: '#fff', border: '1px solid #e1e3e5', borderRadius: 8, fontSize: 12 }}
            labelStyle={{ color: '#202223', fontWeight: 600 }}
            formatter={(v: number) => [fmt(v), seriesLabel]}
          />
          <Bar dataKey="value" name={seriesLabel} fill={color} radius={[4, 4, 0, 0]} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}
