'use client';

import React from 'react';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from 'recharts';

const topProducts = [
  { id: 'prod-chart-001', name: 'Maize Flour 2kg', revenue: 42800, units: 214 },
  { id: 'prod-chart-002', name: 'Cooking Oil 1L', revenue: 31600, units: 158 },
  { id: 'prod-chart-003', name: 'Sugar 1kg', revenue: 28400, units: 284 },
  { id: 'prod-chart-004', name: 'Bread Loaf', revenue: 22100, units: 221 },
  { id: 'prod-chart-005', name: 'Milk 500ml', revenue: 18700, units: 374 },
];

const barColors = ['var(--primary)', '#1e6ab8', '#3d7cc9', '#5e93d8', '#8ab3e8'];

const CustomTooltip = ({ active, payload, label }: { active?: boolean; payload?: Array<{ value: number }>; label?: string }) => {
  if (!active || !payload?.length) return null;
  const product = topProducts.find((p) => p.name === label);
  return (
    <div className="card-elevated rounded-lg p-3 shadow-modal text-xs">
      <p className="font-600 text-foreground mb-2 max-w-32 leading-snug">{label}</p>
      <div className="flex items-center justify-between gap-4">
        <span className="text-muted-foreground">Revenue</span>
        <span className="font-700 text-foreground font-tabular">KES {payload[0].value.toLocaleString()}</span>
      </div>
      {product && (
        <div className="flex items-center justify-between gap-4 mt-1">
          <span className="text-muted-foreground">Units sold</span>
          <span className="font-700 text-foreground font-tabular">{product.units}</span>
        </div>
      )}
    </div>
  );
};

export default function TopProductsChart() {
  return (
    <ResponsiveContainer width="100%" height={240}>
      <BarChart
        data={topProducts}
        layout="vertical"
        margin={{ top: 0, right: 8, left: 4, bottom: 0 }}
        barCategoryGap="25%"
      >
        <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />
        <XAxis
          type="number"
          tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
          axisLine={false}
          tickLine={false}
          tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`}
        />
        <YAxis
          type="category"
          dataKey="name"
          tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
          axisLine={false}
          tickLine={false}
          width={90}
          tickFormatter={(v: string) => v.length > 14 ? v.slice(0, 14) + '…' : v}
        />
        <Tooltip content={<CustomTooltip />} cursor={{ fill: 'var(--muted)', opacity: 0.5 }} />
        <Bar dataKey="revenue" radius={[0, 4, 4, 0]}>
          {topProducts.map((entry, index) => (
            <Cell key={`bar-${entry.id}`} fill={barColors[index]} />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}