import React, { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import Layout from '../../components/Layout';
import { api } from '../../lib/api';
import { toast } from 'sonner';
import {
    ArrowLeft, BarChart3, Calendar, Filter, Users, MapPin, AlertCircle,
    Package, RefreshCw,
} from 'lucide-react';
import {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
    Cell, LineChart, Line,
} from 'recharts';

// Palette of colors used to fall back when no motif_color is defined
const FALLBACK_COLORS = [
    '#F59E0B', '#EF4444', '#10B981', '#3B82F6', '#8B5CF6',
    '#EC4899', '#14B8A6', '#F97316',
];

const labelNorm = (s) => (s || '')
    .trim()
    .toLowerCase()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, ' ')
    .trim();

// Default date range: last 30 days
const isoDate = (d) => d.toISOString().slice(0, 10);
const today = new Date();
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(today.getDate() - 29);

export default function ReliquatsStats() {
    const navigate = useNavigate();
    const [dateFrom, setDateFrom] = useState(isoDate(thirtyDaysAgo));
    const [dateTo, setDateTo] = useState(isoDate(today));
    const [scope, setScope] = useState('all');
    const [loading, setLoading] = useState(true);
    const [data, setData] = useState(null);

    const load = async () => {
        setLoading(true);
        try {
            const r = await api.get('/gp/stats/reliquats', {
                params: { date_from: dateFrom, date_to: dateTo, scope },
            });
            setData(r.data);
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Erreur de chargement');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { load(); /* eslint-disable-next-line */ }, []);

    const colorForMotif = (label, idx) => {
        const map = data?.motif_colors || {};
        // Try exact match, then normalised
        if (map[label]) return map[label];
        const norm = labelNorm(label);
        for (const k of Object.keys(map)) {
            if (labelNorm(k) === norm) return map[k];
        }
        return FALLBACK_COLORS[idx % FALLBACK_COLORS.length];
    };

    const fournisseurs = data?.top_fournisseurs || [];
    const destinations = data?.top_destinations || [];
    const motifs = data?.top_motifs || [];
    const daily = data?.daily || [];
    const totals = data?.totals || { palettes: 0 };

    // Format date labels for the daily line chart (DD/MM)
    const dailySeries = useMemo(() => daily.map((d) => ({
        ...d,
        label: (() => {
            try {
                const dt = new Date(d.date);
                return `${String(dt.getDate()).padStart(2, '0')}/${String(dt.getMonth() + 1).padStart(2, '0')}`;
            } catch { return d.date; }
        })(),
    })), [daily]);

    const quickRange = (days) => {
        const to = new Date();
        const from = new Date();
        from.setDate(to.getDate() - (days - 1));
        setDateFrom(isoDate(from));
        setDateTo(isoDate(to));
    };

    return (
        <Layout>
            <button
                data-testid="back-btn"
                onClick={() => navigate('/palettes/reliquat')}
                className="mb-5 inline-flex items-center gap-2 text-sm font-semibold text-slate-600 hover:text-amber-600 transition"
            >
                <ArrowLeft className="h-4 w-4" />
                Retour aux Palettes Reliquat
            </button>

            <div className="mb-6 flex items-start justify-between gap-4 flex-wrap">
                <div className="flex items-center gap-3">
                    <div className="flex h-11 w-11 items-center justify-center rounded-md bg-amber-100 text-amber-600">
                        <BarChart3 className="h-5 w-5" />
                    </div>
                    <div>
                        <p className="text-xs font-bold uppercase tracking-[0.2em] text-amber-600">Statistiques</p>
                        <h1 className="font-heading text-2xl sm:text-3xl font-black tracking-tight text-slate-900">
                            Reliquats — Tableau de bord
                        </h1>
                    </div>
                </div>
                <button
                    data-testid="stats-refresh-btn"
                    onClick={load}
                    disabled={loading}
                    className="inline-flex items-center gap-2 rounded-md border border-slate-300 bg-white px-4 h-10 text-sm font-bold text-slate-700 hover:bg-slate-50 transition disabled:opacity-50"
                >
                    <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} /> Rafraîchir
                </button>
            </div>

            {/* === Filtres === */}
            <div className="mb-5 rounded-lg border border-slate-200 bg-white p-4 sm:p-5" data-testid="stats-filters-card">
                <div className="flex items-start gap-3 mb-3">
                    <Filter className="h-4 w-4 text-amber-600 mt-1" />
                    <span className="text-[11px] font-bold uppercase tracking-[0.2em] text-slate-600">Filtres</span>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3 items-end">
                    <div>
                        <label className="text-[11px] font-bold uppercase tracking-[0.2em] text-slate-600">Du</label>
                        <input
                            data-testid="stats-date-from"
                            type="date"
                            value={dateFrom}
                            onChange={(e) => setDateFrom(e.target.value)}
                            className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm font-semibold text-slate-900 focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                        />
                    </div>
                    <div>
                        <label className="text-[11px] font-bold uppercase tracking-[0.2em] text-slate-600">Au</label>
                        <input
                            data-testid="stats-date-to"
                            type="date"
                            value={dateTo}
                            onChange={(e) => setDateTo(e.target.value)}
                            className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm font-semibold text-slate-900 focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                        />
                    </div>
                    <div>
                        <label className="text-[11px] font-bold uppercase tracking-[0.2em] text-slate-600">Statut</label>
                        <select
                            data-testid="stats-scope-select"
                            value={scope}
                            onChange={(e) => setScope(e.target.value)}
                            className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm font-semibold text-slate-900 focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                        >
                            <option value="all">Toutes</option>
                            <option value="active">Actives</option>
                            <option value="archived">Archivées</option>
                        </select>
                    </div>
                    <div className="lg:col-span-2 flex flex-wrap gap-2">
                        <button
                            data-testid="stats-apply-btn"
                            onClick={load}
                            disabled={loading}
                            className="inline-flex items-center justify-center gap-2 rounded-md bg-amber-500 text-white px-5 h-11 text-sm font-heading font-bold hover:bg-amber-600 active:scale-[0.99] transition-all disabled:opacity-50"
                        >
                            <Filter className="h-4 w-4" /> Appliquer
                        </button>
                        <div className="flex gap-1 flex-wrap">
                            {[
                                { d: 7, l: '7j' },
                                { d: 30, l: '30j' },
                                { d: 90, l: '90j' },
                                { d: 365, l: '1 an' },
                            ].map((r) => (
                                <button
                                    key={r.d}
                                    data-testid={`stats-quick-${r.d}`}
                                    onClick={() => quickRange(r.d)}
                                    className="rounded-md border border-slate-300 bg-white px-3 h-11 text-xs font-bold text-slate-700 hover:bg-slate-50 transition"
                                >
                                    {r.l}
                                </button>
                            ))}
                        </div>
                    </div>
                </div>
            </div>

            {/* === KPIs === */}
            <div className="mb-5 grid grid-cols-1 sm:grid-cols-3 gap-3">
                <KpiCard
                    icon={<Package className="h-4 w-4" />}
                    label="Total palettes"
                    value={totals.palettes}
                    testid="stats-kpi-palettes"
                />
                <KpiCard
                    icon={<Users className="h-4 w-4" />}
                    label="Fournisseurs"
                    value={fournisseurs.length}
                    testid="stats-kpi-fournisseurs"
                />
                <KpiCard
                    icon={<MapPin className="h-4 w-4" />}
                    label="Destinations"
                    value={destinations.length}
                    testid="stats-kpi-destinations"
                />
            </div>

            {loading ? (
                <div className="rounded-lg border border-slate-200 bg-white p-12 text-center text-slate-500">
                    Chargement…
                </div>
            ) : (
                <>
                    {/* === Daily evolution line chart === */}
                    <div
                        className="mb-5 rounded-lg border border-slate-200 bg-white p-5 sm:p-6"
                        data-testid="stats-daily-card"
                    >
                        <div className="flex items-start gap-3 mb-4">
                            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-amber-100 text-amber-600">
                                <Calendar className="h-5 w-5" />
                            </div>
                            <div>
                                <h2 className="font-heading text-lg font-bold text-slate-900">Évolution quotidienne</h2>
                                <p className="text-sm text-slate-500 mt-0.5">
                                    Nombre de palettes saisies par jour sur la période.
                                </p>
                            </div>
                        </div>
                        <div className="h-72">
                            {dailySeries.length === 0 ? (
                                <EmptyChart />
                            ) : (
                                <ResponsiveContainer width="100%" height="100%">
                                    <LineChart data={dailySeries} margin={{ top: 5, right: 12, left: -6, bottom: 0 }}>
                                        <CartesianGrid stroke="#E2E8F0" strokeDasharray="3 3" />
                                        <XAxis dataKey="label" tick={{ fontSize: 11, fill: '#64748B' }} />
                                        <YAxis tick={{ fontSize: 11, fill: '#64748B' }} allowDecimals={false} />
                                        <Tooltip
                                            contentStyle={{
                                                background: 'rgba(255,255,255,0.95)',
                                                border: '1px solid #E2E8F0',
                                                borderRadius: 8,
                                                fontSize: 12,
                                            }}
                                            formatter={(v) => [v, 'Palettes']}
                                        />
                                        <Line
                                            type="monotone"
                                            dataKey="total"
                                            name="Palettes"
                                            stroke="#F59E0B"
                                            strokeWidth={2.5}
                                            dot={{ r: 3, fill: '#F59E0B' }}
                                            activeDot={{ r: 5 }}
                                        />
                                    </LineChart>
                                </ResponsiveContainer>
                            )}
                        </div>
                    </div>

                    {/* === Top 5 charts grid === */}
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
                        <TopChart
                            title="Top 5 Fournisseurs"
                            icon={<Users className="h-5 w-5" />}
                            rows={fournisseurs}
                            color="#3B82F6"
                            testid="stats-top-fournisseurs"
                            useMotifColors={false}
                        />
                        <TopChart
                            title="Top 5 Destinations"
                            icon={<MapPin className="h-5 w-5" />}
                            rows={destinations}
                            color="#10B981"
                            testid="stats-top-destinations"
                            useMotifColors={false}
                        />
                        <TopChart
                            title="Top 5 Motifs"
                            icon={<AlertCircle className="h-5 w-5" />}
                            rows={motifs}
                            color="#F59E0B"
                            testid="stats-top-motifs"
                            useMotifColors
                            colorForMotif={colorForMotif}
                        />
                    </div>
                </>
            )}
        </Layout>
    );
}

function KpiCard({ icon, label, value, testid }) {
    return (
        <div
            data-testid={testid}
            className="rounded-lg border border-slate-200 bg-white p-4 flex items-center gap-3"
        >
            <div className="flex h-9 w-9 items-center justify-center rounded-md bg-amber-100 text-amber-600 shrink-0">
                {icon}
            </div>
            <div className="min-w-0">
                <p className="text-[11px] font-bold uppercase tracking-[0.15em] text-slate-500 truncate">{label}</p>
                <p className="font-heading text-2xl font-black tracking-tight text-slate-900 leading-none mt-1">
                    {value.toLocaleString('fr-FR')}
                </p>
            </div>
        </div>
    );
}

function EmptyChart() {
    return (
        <div className="h-full w-full flex items-center justify-center text-sm text-slate-400 italic">
            Aucune donnée pour cette période.
        </div>
    );
}

function TopChart({ title, icon, rows, color, testid, useMotifColors, colorForMotif }) {
    // Recharts horizontal bar chart
    const data = (rows || []).map((r) => ({
        name: r.label,
        total: r.total,
    }));
    return (
        <div
            data-testid={testid}
            className="rounded-lg border border-slate-200 bg-white p-5 sm:p-6"
        >
            <div className="flex items-start gap-3 mb-4">
                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-amber-100 text-amber-600">
                    {icon}
                </div>
                <div>
                    <h2 className="font-heading text-base font-bold text-slate-900">{title}</h2>
                    <p className="text-xs text-slate-500 mt-0.5">Par nombre de palettes.</p>
                </div>
            </div>
            <div className="h-64">
                {data.length === 0 ? (
                    <EmptyChart />
                ) : (
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart
                            data={data}
                            layout="vertical"
                            margin={{ top: 5, right: 16, left: 4, bottom: 0 }}
                        >
                            <CartesianGrid stroke="#E2E8F0" strokeDasharray="3 3" horizontal={false} />
                            <XAxis type="number" tick={{ fontSize: 11, fill: '#64748B' }} allowDecimals={false} />
                            <YAxis
                                type="category"
                                dataKey="name"
                                width={110}
                                tick={{ fontSize: 11, fill: '#1E293B', fontWeight: 600 }}
                                interval={0}
                            />
                            <Tooltip
                                contentStyle={{
                                    background: 'rgba(255,255,255,0.95)',
                                    border: '1px solid #E2E8F0',
                                    borderRadius: 8,
                                    fontSize: 12,
                                }}
                                formatter={(v) => [v, 'Palettes']}
                            />
                            <Bar dataKey="total" radius={[0, 6, 6, 0]} maxBarSize={28}>
                                {data.map((entry, idx) => (
                                    <Cell
                                        key={`c-${idx}`}
                                        fill={useMotifColors && colorForMotif
                                            ? colorForMotif(entry.name, idx)
                                            : color}
                                    />
                                ))}
                            </Bar>
                        </BarChart>
                    </ResponsiveContainer>
                )}
            </div>

            {/* Legend table under chart */}
            {data.length > 0 && (
                <div className="mt-3 space-y-1.5">
                    {data.map((d, idx) => (
                        <div key={d.name} className="flex items-center justify-between gap-2 text-xs">
                            <div className="flex items-center gap-2 min-w-0 flex-1">
                                <span
                                    className="inline-block h-2.5 w-2.5 rounded-sm shrink-0"
                                    style={{
                                        background: useMotifColors && colorForMotif
                                            ? colorForMotif(d.name, idx)
                                            : color,
                                    }}
                                />
                                <span className="font-semibold text-slate-700 truncate">{d.name}</span>
                            </div>
                            <span className="font-bold text-slate-900 tabular-nums">
                                {d.total.toLocaleString('fr-FR')}
                            </span>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
