import { BarChart3, Layers, TrendingUp } from 'lucide-react';
import { Bar, BarChart, CartesianGrid, Cell, Legend, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { INK, Panel, tooltipStyle } from '@/components/dashboard';
import { int, mesCorto, money, moneyShort, pct, toNum } from '@/lib/format';

export type Item = { name: string; value: number | string; pct: number | string };
export type MonthRow = { mes: string; [grupo: string]: number | string };

/* Grupos de producto: colores oficiales fijos por entidad (tokens en app.css), nunca por posición. */
export const GRUPOS: { key: string; label: string; color: string }[] = [
    { key: 'ETICOS', label: 'Éticos', color: 'var(--grupo-eticos)' },
    { key: 'GENERICOS', label: 'Genéricos', color: 'var(--grupo-genericos)' },
    { key: 'OTC', label: 'OTC', color: 'var(--grupo-otc)' },
    { key: 'MAQUILA', label: 'Maquila', color: 'var(--chart-4)' },
    // Pizarra oscuro: un gris claro se confundiría con el azul de Genéricos.
    { key: 'OTROS', label: 'Otros', color: 'var(--chart-5)' },
];

/* Zonas: colores oficiales. */
export const ZONAS: Record<string, string> = { 'ZONA 1': 'var(--zona-1)', 'ZONA 2': 'var(--zona-2)' };


/* Líneas médicas: color fijo según su posición en la lista completa de líneas (no en el ranking). */
const COLORES_LINEA = ['#6366f1', '#8b5cf6', '#ec4899', '#14b8a6', '#f59e0b', '#3b82f6', '#22c55e', '#ef4444', '#06b6d4', '#a3a3a3', '#84cc16', '#f97316'];

/** Barras apiladas por grupo de producto, mes a mes. */
export function MonthlyByGroupChart({ rows, year, unidades, title, accent = '#3b82f6' }: { rows: MonthRow[]; year?: number | string; unidades: boolean; title: string; accent?: string }) {
    const meses: Record<string, string | number>[] = rows.map((r) => ({
        mes: r.mes,
        mesLabel: mesCorto(r.mes),
        ...Object.fromEntries(GRUPOS.map((g) => [g.key, toNum(r[g.key])])),
    }));
    const conDatos = GRUPOS.filter((g) => meses.some((m) => toNum(m[g.key]) > 0));
    const rango = meses.length ? `${mesCorto(String(meses[0]!.mes))} a ${mesCorto(String(meses[meses.length - 1]!.mes))} ${year ?? ''}` : '';

    return (
        <Panel title={`${title} · ${year ?? ''}`} icon={<BarChart3 className="size-4" />} accent={accent} right={rango}>
            <div className="h-80">
                <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={meses} barCategoryGap="22%">
                        <CartesianGrid vertical={false} stroke={INK.grid} />
                        <XAxis dataKey="mesLabel" tickLine={false} axisLine={{ stroke: INK.axis }} tick={{ fill: INK.muted, fontSize: 12 }} />
                        <YAxis tickLine={false} axisLine={false} width={80} tick={{ fill: INK.muted, fontSize: 12 }} tickFormatter={(v) => (unidades ? int(v) : moneyShort(v))} />
                        <Tooltip
                            cursor={{ fill: 'rgba(91,76,230,0.06)' }}
                            formatter={(v, name) => [unidades ? int(v) : money(v), GRUPOS.find((g) => g.key === name)?.label ?? String(name)]}
                            labelStyle={{ color: INK.primary, fontWeight: 700 }}
                            contentStyle={tooltipStyle}
                        />
                        <Legend formatter={(v) => <span style={{ color: INK.secondary, fontSize: 12 }}>{GRUPOS.find((g) => g.key === v)?.label ?? v}</span>} />
                        {conDatos.map((g, i) => (
                            <Bar key={g.key} dataKey={g.key} stackId="g" fill={g.color} stroke="#ffffff" strokeWidth={2} radius={i === conDatos.length - 1 ? [4, 4, 0, 0] : 0} />
                        ))}
                    </BarChart>
                </ResponsiveContainer>
            </div>
        </Panel>
    );
}

/** Dona + lista de participación por línea médica. */
export function MixLineas({ items, todas, unidades, title = 'Mix de ventas por línea', pctColor = 'text-brand' }: { items: Item[]; todas: string[]; unidades: boolean; title?: string; pctColor?: string }) {
    const color = (name: string) => {
        const i = todas.indexOf(name);
        return COLORES_LINEA[(i >= 0 ? i : todas.length) % COLORES_LINEA.length]!;
    };
    const data = items.map((i) => ({ name: i.name, value: toNum(i.value), pct: toNum(i.pct) }));

    return (
        <Panel title={title} icon={<Layers className="size-4" />} accent="#f97316" right={`${items.length} líneas`}>
            <div className="grid grid-cols-1 gap-3 md:grid-cols-[1fr_1.3fr]">
                <div className="grid h-72 place-items-center rounded-xl bg-slate-50">
                    <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                            <Pie data={data} dataKey="value" nameKey="name" innerRadius="48%" outerRadius="72%" stroke="#ffffff" strokeWidth={2}>
                                {data.map((d) => (
                                    <Cell key={d.name} fill={color(d.name)} />
                                ))}
                            </Pie>
                            <Tooltip formatter={(v, n, p) => [`${unidades ? int(v) : money(v)} · ${pct((p.payload as { pct: number }).pct)}`, String(n)]} contentStyle={tooltipStyle} />
                        </PieChart>
                    </ResponsiveContainer>
                </div>
                <div className="rounded-xl border border-slate-100 p-2">
                    <div className="flex justify-between px-2 pb-1 text-[10px] font-semibold tracking-wider text-slate-400 uppercase">
                        <span>Participación</span>
                        <span>{unidades ? 'Unid.' : 'RD$'}</span>
                    </div>
                    <ul className="max-h-60 space-y-1 overflow-y-auto pr-1">
                        {data.map((d) => (
                            <li key={d.name} className="flex items-center justify-between rounded-lg bg-slate-50 px-2 py-1.5 text-[11px]">
                                <span className="flex items-center gap-2 font-semibold text-slate-700">
                                    <span className="size-2.5 rounded-full" style={{ background: color(d.name) }} />
                                    {d.name}
                                </span>
                                <span className="text-right tabular-nums">
                                    <span className={`block font-bold ${pctColor}`}>{pct(d.pct)}</span>
                                    <span className="block text-[10px] text-slate-400">{unidades ? int(d.value) : moneyShort(d.value)}</span>
                                </span>
                            </li>
                        ))}
                        {data.length === 0 && <li className="p-2 text-sm text-slate-400">Sin datos para el periodo.</li>}
                    </ul>
                </div>
            </div>
        </Panel>
    );
}

/** Ranking horizontal por provincia con dos recuadros de resumen arriba. */
export function RankingProvincias({
    items,
    unidades,
    title = 'Ventas por provincia',
    tiles,
    tileSubClass = 'text-[#006300]',
}: {
    items: Item[];
    unidades: boolean;
    title?: string;
    tiles: { label: string; value: string; sub: string }[];
    tileSubClass?: string;
}) {
    const data = items.map((i) => ({ name: i.name, value: toNum(i.value), pct: toNum(i.pct) }));
    return (
        <Panel title={title} icon={<TrendingUp className="size-4" />} accent="#8b5cf6" right={`${items.length} provincias`}>
            <div className="mb-3 grid grid-cols-2 gap-3">
                {tiles.map((t) => (
                    <div key={t.label} className="rounded-xl border border-slate-100 p-3">
                        <p className="text-[10px] font-semibold tracking-wider text-slate-400 uppercase">{t.label}</p>
                        <p className="text-lg font-extrabold">{t.value}</p>
                        <p className={`text-[11px] font-semibold ${tileSubClass}`}>{t.sub}</p>
                    </div>
                ))}
            </div>
            <div className="h-56 overflow-y-auto rounded-xl bg-slate-50 pr-1">
                <div style={{ height: Math.max(data.length * 34, 200) }}>
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={data} layout="vertical" margin={{ left: 8, right: 16, top: 8, bottom: 8 }}>
                            <XAxis type="number" hide />
                            <YAxis type="category" dataKey="name" width={130} tickLine={false} axisLine={false} interval={0} tick={{ fill: INK.secondary, fontSize: 10, fontWeight: 600 }} />
                            <Tooltip
                                cursor={{ fill: 'rgba(91,76,230,0.06)' }}
                                formatter={(v, _n, p) => [`${unidades ? int(v) : money(v)} · ${pct((p.payload as { pct: number }).pct)}`, unidades ? 'Unidades' : 'Monto']}
                                contentStyle={tooltipStyle}
                            />
                            <Bar dataKey="value" fill="#6366f1" radius={[0, 4, 4, 0]} barSize={22} />
                        </BarChart>
                    </ResponsiveContainer>
                </div>
            </div>
        </Panel>
    );
}
