import React, { useEffect, useState } from 'react';
import Layout from '../components/Layout';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { api } from '../lib/api';
import { Truck, Boxes, ArrowRight, FolderPlus, History, Archive, RotateCcw, TrendingUp, Clock } from 'lucide-react';

function Card({ icon: Icon, accent, title, desc, onClick, testid, badge }) {
    return (
        <button
            data-testid={testid}
            onClick={onClick}
            className={`group text-left rounded-xl border-2 border-slate-200 bg-white p-5 sm:p-6 hover:-translate-y-1 hover:shadow-xl transition-all duration-300 ${accent === 'amber' ? 'hover:border-amber-500' : 'hover:border-stef'}`}
        >
            <div className="flex items-start justify-between gap-3">
                <div className={`flex h-12 w-12 sm:h-14 sm:w-14 items-center justify-center rounded-lg ring-2 transition ${
                    accent === 'amber'
                        ? 'bg-amber-500/10 ring-amber-500/20 group-hover:bg-amber-500 group-hover:ring-amber-500/40'
                        : 'bg-stef/10 ring-stef/20 group-hover:bg-stef group-hover:ring-stef/40'
                }`}>
                    <Icon className={`h-6 w-6 sm:h-7 sm:w-7 transition ${accent === 'amber' ? 'text-amber-600 group-hover:text-white' : 'text-stef group-hover:text-white'}`} />
                </div>
                <div className="flex items-center gap-2">
                    {badge != null && (
                        <span className={`inline-flex items-center justify-center rounded-full px-2.5 h-6 text-[11px] font-black ${accent === 'amber' ? 'bg-amber-500 text-white' : 'bg-stef text-white'}`}>
                            {badge}
                        </span>
                    )}
                    <ArrowRight className={`h-4 w-4 text-slate-300 group-hover:translate-x-1 transition-all ${accent === 'amber' ? 'group-hover:text-amber-600' : 'group-hover:text-stef'}`} />
                </div>
            </div>
            <h3 className="mt-4 font-heading text-lg sm:text-xl font-black tracking-tight text-slate-900">{title}</h3>
            <p className="mt-1 text-sm text-slate-600 leading-relaxed">{desc}</p>
        </button>
    );
}

function MiniStat({ icon: Icon, label, value, accent }) {
    return (
        <div className="rounded-lg border border-slate-200 bg-white px-4 py-3 flex items-center gap-3">
            <div className={`flex h-9 w-9 items-center justify-center rounded-md ${accent === 'amber' ? 'bg-amber-50 text-amber-700' : 'bg-stef/5 text-stef'}`}>
                <Icon className="h-4 w-4" />
            </div>
            <div className="min-w-0">
                <p className="text-[10px] font-bold uppercase tracking-wider text-slate-500 truncate">{label}</p>
                <p className="font-heading text-xl font-black text-slate-900 leading-none mt-1">{value}</p>
            </div>
        </div>
    );
}

export default function Hub() {
    const { user } = useAuth();
    const navigate = useNavigate();
    const isBureau = user?.role === 'bureau';
    const [gpStats, setGpStats] = useState(null);

    useEffect(() => {
        if (!isBureau) return;
        api.get('/gp/stats/24h')
            .then((r) => setGpStats(r.data))
            .catch(() => setGpStats({ palettes_active: 0, palettes_24h: 0, palettes_archived_24h: 0, sav_24h: 0, sav_total: 0 }));
    }, [isBureau]);

    return (
        <Layout>
            <div className="mb-8 sm:mb-10">
                <p className="text-xs font-bold uppercase tracking-[0.2em] text-stef">Accueil</p>
                <h1 className="mt-2 font-heading text-3xl sm:text-4xl lg:text-5xl font-black tracking-tight text-slate-900">
                    Bonjour {user?.fullname || user?.username}
                </h1>
                <p className="mt-2 text-sm sm:text-base text-slate-600">Choisis ce que tu veux faire aujourd'hui.</p>
            </div>

            {/* My Truck section */}
            <section className="mb-10">
                <div className="mb-4 flex items-center gap-3">
                    <div className="flex h-8 w-8 items-center justify-center rounded-md bg-stef/10">
                        <Truck className="h-4 w-4 text-stef" />
                    </div>
                    <h2 className="font-heading text-base sm:text-lg font-black uppercase tracking-wider text-slate-900">Dossier Camion</h2>
                    <div className="flex-1 h-px bg-slate-200" />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    <Card icon={Truck}      accent="stef" title="Tableau de bord"   desc="Dossiers du jour et statistiques." onClick={() => navigate('/truck')}      testid="hub-truck" />
                    <Card icon={FolderPlus} accent="stef" title="Nouveau dossier"   desc="Signaler un problème camion."        onClick={() => navigate('/new-folder')} testid="hub-new-folder" />
                    <Card icon={History}    accent="stef" title="Historique"        desc="Tous les dossiers archivés."         onClick={() => navigate('/history')}    testid="hub-history" />
                </div>
            </section>

            {/* Gestion Palettes — bureau only */}
            {isBureau && (
                <section>
                    <div className="mb-4 flex items-center gap-3">
                        <div className="flex h-8 w-8 items-center justify-center rounded-md bg-amber-500/10">
                            <Boxes className="h-4 w-4 text-amber-600" />
                        </div>
                        <h2 className="font-heading text-base sm:text-lg font-black uppercase tracking-wider text-slate-900">Gestion Palettes</h2>
                        <span className="hidden sm:inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-slate-400">
                            <Clock className="h-3 w-3" /> 24 dernières heures
                        </span>
                        <div className="flex-1 h-px bg-slate-200" />
                    </div>

                    {/* Mini stats */}
                    {gpStats && (
                        <div className="mb-4 grid grid-cols-2 sm:grid-cols-4 gap-3" data-testid="gp-stats-24h">
                            <MiniStat icon={Archive}    accent="amber" label="Reliquats actifs"  value={gpStats.palettes_active} />
                            <MiniStat icon={TrendingUp} accent="amber" label="Saisis 24h"        value={gpStats.palettes_24h} />
                            <MiniStat icon={RotateCcw}  accent="amber" label="Retours 24h"       value={gpStats.sav_24h} />
                            <MiniStat icon={Boxes}      accent="amber" label="Retours total"     value={gpStats.sav_total} />
                        </div>
                    )}

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <Card icon={Archive}   accent="amber" title="Palettes Reliquat"    desc="Liste des reliquats actifs. Archivage auto à 6h01." onClick={() => navigate('/palettes/reliquat')} testid="hub-reliquat" badge={gpStats?.palettes_active} />
                        <Card icon={RotateCcw} accent="amber" title="Retours Fournisseurs" desc="SAV et organisation des retours."                   onClick={() => navigate('/palettes/sav')}      testid="hub-sav" />
                    </div>
                </section>
            )}
        </Layout>
    );
}
