import { memo, useMemo } from 'react';
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from 'recharts';
import { Card } from '@/components/ui/card';
import { getStockAgeDistribution } from '@/lib/mockData';

const COLORS = ['#4ade80', '#60a5fa', '#fbbf24', '#f87171', '#a78bfa', '#38bdf8', '#fb923c'];

export const StockAgeChart = memo(({ data }: { data?: any[] }) => {
  const stockAgeData = useMemo(() => {
    if (data && data.length > 0) {
      return data.map(d => ({
        range: d.age_range,
        value: d.percentage
      })).filter(d => d.value > 0); // Only show segments with value > 0
    }
    return getStockAgeDistribution();
  }, [data]);

  return (
    <Card className="p-4 sm:h-[280px]">
      <h3 className="text-lg font-semibold mb-2 text-foreground">Stock Age Distribution</h3>
      <div className="flex flex-col sm:flex-row items-center gap-x-2 gap-y-4 h-full justify-center">
        <div className="w-[140px] h-[140px] flex-shrink-0">
          <ResponsiveContainer width="100%" height="100%">
            <PieChart>
              <Pie
                data={stockAgeData}
                cx="50%"
                cy="50%"
                labelLine={false}
                outerRadius={60}
                innerRadius={30}
                fill="#8884d8"
                dataKey="value"
              >
                {stockAgeData.map((_, index) => (
                  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </ResponsiveContainer>
        </div>
        <div className="flex-1 min-w-0 flex flex-col justify-center">
          <div className="grid grid-cols-2 gap-x-2 gap-y-2">
            {stockAgeData.map((entry, index) => (
              <div key={index} className="flex items-center gap-1.5 min-w-0">
                <div
                  className="w-2.5 h-2.5 rounded-sm flex-shrink-0"
                  style={{ backgroundColor: COLORS[index % COLORS.length] }}
                />
                <span className="text-[10px] text-foreground font-medium truncate" title={`${entry.range} Days: ${entry.value}%`}>
                  {entry.range} Days: <span className="text-muted-foreground font-normal">{entry.value}%</span>
                </span>
              </div>
            ))}
            {stockAgeData.length === 0 && (
              <div className="col-span-2 text-center text-sm text-muted-foreground">
                No stock data available
              </div>
            )}
          </div>
        </div>
      </div>
    </Card>
  );
});

StockAgeChart.displayName = 'StockAgeChart';
