import { useState, useEffect } from 'react';
import { reportService, type CategorySales } from '../../services/reportService';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell } from 'recharts';
import { LayoutGrid, Calendar, ArrowRight } from 'lucide-react';

const COLORS = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899'];

export default function SalesByCategory() {
  const [data, setData] = useState<CategorySales[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const res = await reportService.getSalesByCategory();
      setData(res);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  if (loading) return (
    <div className="flex items-center justify-center h-64 text-slate-400 font-bold uppercase tracking-widest text-xs">
      Cargando analíticas...
    </div>
  );

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-2">
          <LayoutGrid className="text-blue-600" />
          Rendimiento por Rubro
        </h2>
        <div className="flex gap-2 items-center bg-white p-2 rounded-lg border text-sm">
          <Calendar size={16} className="text-gray-400" />
          <span className="text-gray-600">Últimos 30 días</span>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Gráfico de Barras */}
        <div className="lg:col-span-2 bg-white p-6 rounded-xl border shadow-sm">
          <h3 className="font-bold text-gray-700 mb-6">Ingresos Totales por Rubro (Consolidado)</h3>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={data} layout="vertical" margin={{ left: 30, right: 30 }}>
                <CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#F3F4F6" />
                <XAxis type="number" hide />
                <YAxis
                  dataKey="categoryName"
                  type="category"
                  axisLine={false}
                  tickLine={false}
                  width={100}
                  tick={{ fill: '#4B5563', fontSize: 12, fontWeight: 600 }}
                />
                <Tooltip
                  formatter={(value: number | undefined) => value ? [`$${value.toLocaleString()}`, 'Ventas'] : ['-', 'Ventas']}
                  cursor={{ fill: '#F9FAFB' }}
                />
                <Bar dataKey="totalSales" radius={[0, 4, 4, 0]} barSize={30}>
                  {data.map((_, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Resumen Lateral */}
        <div className="bg-white p-6 rounded-xl border shadow-sm flex flex-col">
          <h3 className="font-bold text-gray-700 mb-4">Top Participación</h3>
          <div className="space-y-4 flex-1">
            {data.map((item, index) => (
              <div key={item.categoryId} className="group cursor-default">
                <div className="flex justify-between text-sm mb-1">
                  <span className="font-medium text-gray-600">{item.categoryName}</span>
                  <span className="font-bold text-gray-900">{item.percentage}%</span>
                </div>
                <div className="w-full bg-gray-100 rounded-full h-2">
                  <div
                    className="h-2 rounded-full transition-all duration-500"
                    style={{
                      width: `${item.percentage}%`,
                      backgroundColor: COLORS[index % COLORS.length]
                    }}
                  ></div>
                </div>
                <div className="flex justify-between mt-1">
                  <span className="text-[10px] text-gray-400 uppercase">{item.adCount} avisos</span>
                  <span className="text-[10px] font-bold text-gray-500">${item.totalSales.toLocaleString()}</span>
                </div>
              </div>
            ))}
          </div>
          <button className="mt-6 w-full py-2 bg-gray-50 text-gray-600 text-xs font-bold rounded-lg border border-gray-100 hover:bg-gray-100 flex items-center justify-center gap-2">
            DESCARGAR DETALLE <ArrowRight size={14} />
          </button>
        </div>
      </div>
    </div>
  );
}