import React, { useEffect, useState, useCallback } from 'react';
import Layout from '../components/Layout';
import api from '../lib/api';
import { useAuth } from '../context/AuthContext';
import { toast } from 'sonner';
import { RefreshCw, Trash2, Brush, ExternalLink } from 'lucide-react';

const DOORS = Array.from({ length: 27 }, (_, i) => `T${i + 2}`); // T2..T28
const XD_BASE = "https://tf-stb-kl.xdock.de";

const fmtFR = (mysql) => {
    if (!mysql) return '';
    const [d, t = '00:00:00'] = String(mysql).split(' ');
    const [Y, M, D] = d.split('-');
    const [h, m] = t.split(':');
    return `${D}.${M}.${Y} ${h}:${m}`;
};

export default function XDockPortesMap() {
    const { user } = useAuth();
    const [counts, setCounts] = useState({});
    const [selectedDoor, setSelectedDoor] = useState('');
    const [rows, setRows] = useState([]);
    const [loading, setLoading] = useState(false);
    const [busy, setBusy] = useState(false);

    const isAllowed = user?.username === 'mathieu.u';

    const loadCounts = useCallback(async () => {
        try {
            const r = await api.get('/xdock/histo-portes?action=counts');
            setCounts(r.data?.counts || {});
        } catch (e) {
            toast.error('Erreur chargement counts: ' + (e?.response?.data?.error || e.message));
        }
    }, []);

    const loadList = useCallback(async (porte) => {
        setLoading(true);
        try {
            const r = await api.get(`/xdock/histo-portes?action=list&porte=${encodeURIComponent(porte)}&limit=10`);
            const list = (r.data?.rows || []).slice().sort((a, b) => {
                const ta = new Date((a.mise_quai || a.arrivee || '').replace(' ', 'T')).getTime() || 0;
                const tb = new Date((b.mise_quai || b.arrivee || '').replace(' ', 'T')).getTime() || 0;
                return tb - ta;
            });
            setRows(list);
        } catch (e) {
            toast.error('Erreur list: ' + (e?.response?.data?.error || e.message));
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => { if (isAllowed) loadCounts(); }, [isAllowed, loadCounts]);

    const onDoorClick = (porte) => {
        setSelectedDoor(porte);
        loadList(porte);
    };

    const clearDoor = async (porte) => {
        if (!confirm(`Vider toutes les entrées de la porte ${porte} (24h) ?`)) return;
        setBusy(true);
        try {
            const fd = new FormData();
            fd.set('action', 'clear');
            fd.set('porte', porte);
            await api.post('/xdock/histo-portes', fd);
            toast.success(`Porte ${porte} vidée`);
            await loadCounts();
            await loadList(porte);
        } catch (e) {
            toast.error('Erreur clear: ' + (e?.response?.data?.error || e.message));
        } finally {
            setBusy(false);
        }
    };

    if (!isAllowed) {
        return (
            <Layout>
                <div className="p-8 text-center text-slate-600">
                    Page réservée à <code className="px-2 py-1 bg-slate-100 rounded">mathieu.u</code>.
                </div>
            </Layout>
        );
    }

    return (
        <Layout>
            <div className="p-6 max-w-7xl mx-auto" data-testid="xdock-portes-map-page">
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-slate-900">MAP des portes — Historique 24h</h1>
                        <p className="text-sm text-slate-500 mt-1">Endpoint NAS <code>/api/xdock/histo-portes</code></p>
                    </div>
                    <button
                        data-testid="xdock-portes-refresh"
                        onClick={loadCounts}
                        className="flex items-center gap-2 px-4 py-2 bg-stef text-white rounded-lg hover:bg-stef/90 transition"
                    >
                        <RefreshCw size={16} /> Actualiser
                    </button>
                </div>

                <div className="grid lg:grid-cols-12 gap-6">
                    {/* Grille des portes */}
                    <div className="lg:col-span-7">
                        <div className="grid grid-cols-7 sm:grid-cols-9 gap-2">
                            {DOORS.map((p) => {
                                const n = counts[p] || 0;
                                const isActive = selectedDoor === p;
                                return (
                                    <button
                                        key={p}
                                        data-testid={`xdock-portes-door-${p}`}
                                        onClick={() => onDoorClick(p)}
                                        className={`relative h-16 rounded-lg border-2 font-bold text-slate-700 transition-all hover:scale-105 ${
                                            isActive
                                                ? 'border-stef bg-stef/10 ring-2 ring-stef/30'
                                                : n > 0
                                                    ? 'border-emerald-400 bg-emerald-50'
                                                    : 'border-slate-200 bg-white hover:border-slate-300'
                                        }`}
                                    >
                                        {p}
                                        {n > 0 && (
                                            <span className="absolute top-1 right-1 text-xs font-bold bg-emerald-600 text-white rounded-full px-1.5 py-0.5 min-w-[20px]">
                                                {n}
                                            </span>
                                        )}
                                    </button>
                                );
                            })}
                        </div>
                    </div>

                    {/* Détail côté droit */}
                    <div className="lg:col-span-5">
                        <div className="bg-white border border-slate-200 rounded-xl p-4 min-h-[400px]">
                            {!selectedDoor ? (
                                <div className="text-sm text-slate-500 text-center py-12">
                                    Clique une porte pour voir l'historique des 24 dernières heures.
                                </div>
                            ) : (
                                <>
                                    <div className="flex items-center justify-between mb-4">
                                        <h2 className="font-bold text-slate-900">Porte {selectedDoor}</h2>
                                        <button
                                            data-testid="xdock-portes-clear-door"
                                            disabled={busy}
                                            onClick={() => clearDoor(selectedDoor)}
                                            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-md hover:bg-amber-100 disabled:opacity-50"
                                        >
                                            <Brush size={12} /> Vider
                                        </button>
                                    </div>
                                    {loading ? (
                                        <div className="text-sm text-slate-500 text-center py-8">Chargement…</div>
                                    ) : rows.length === 0 ? (
                                        <div className="text-sm text-slate-500 text-center py-8">Aucun passage sur 24h.</div>
                                    ) : (
                                        <div className="space-y-2">
                                            {rows.map((r, i) => (
                                                <div key={i} className="border border-slate-100 rounded-lg p-3 hover:bg-slate-50">
                                                    <div className="flex items-center justify-between mb-1">
                                                        <span className="text-xs font-mono text-slate-600">
                                                            {fmtFR(r.mise_quai || r.arrivee)}
                                                        </span>
                                                        <div className="flex gap-1">
                                                            {r.em_id && (
                                                                <a
                                                                    href={`${XD_BASE}/Wareneingang/Tour?weTourId=${r.em_id}`}
                                                                    target="_blank" rel="noopener noreferrer"
                                                                    className="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded font-bold inline-flex items-center gap-1"
                                                                >EM {r.em_id} <ExternalLink size={10} /></a>
                                                            )}
                                                            {r.sm_id && (
                                                                <a
                                                                    href={`${XD_BASE}/Warenausgang/Tour?waTourId=${r.sm_id}`}
                                                                    target="_blank" rel="noopener noreferrer"
                                                                    className="text-xs bg-purple-50 text-purple-700 px-2 py-0.5 rounded font-bold inline-flex items-center gap-1"
                                                                >SM {r.sm_id} <ExternalLink size={10} /></a>
                                                            )}
                                                        </div>
                                                    </div>
                                                    <div className="text-sm text-slate-900 font-medium">{r.transitaire || '-'}</div>
                                                    <div className="text-xs text-slate-600 mt-1">
                                                        <span className="font-mono">{r.tracteur || '-'}</span>
                                                        {' / '}
                                                        <span className="font-mono">{r.remorque || '-'}</span>
                                                        {r.telephone && <span className="ml-2">📞 {r.telephone}</span>}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </Layout>
    );
}
