import React, { useEffect, useMemo, useState } from 'react';
import Layout from '../components/Layout';
import { api } from '../lib/api';
import { useNavigate } from 'react-router-dom';
import StatusBadge from '../components/StatusBadge';
import { History as HistoryIcon, Truck, Search, X } from 'lucide-react';
import { cleanPlate } from '../lib/plate';

const PAGE_SIZE = 50;

export default function HistoryPage() {
    const [folders, setFolders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [query, setQuery] = useState('');
    const [visible, setVisible] = useState(PAGE_SIZE);
    const navigate = useNavigate();

    useEffect(() => {
        api.get('/folders').then(r => setFolders(r.data)).finally(() => setLoading(false));
    }, []);

    // Reset pagination whenever the search query changes
    useEffect(() => { setVisible(PAGE_SIZE); }, [query]);

    const filtered = useMemo(() => {
        const q = cleanPlate(query).trim();
        if (!q) return folders;
        return folders.filter((f) => (f.plate || '').toUpperCase().includes(q));
    }, [folders, query]);

    const shown = filtered.slice(0, visible);
    const hasMore = visible < filtered.length;

    const groups = shown.reduce((acc, f) => {
        const k = f.date_key || (f.created_at || '').slice(0, 10);
        if (!acc[k]) acc[k] = [];
        acc[k].push(f);
        return acc;
    }, {});
    const sortedKeys = Object.keys(groups).sort((a, b) => (a < b ? 1 : -1));

    return (
        <Layout>
            <div className="mb-6 sm:mb-8">
                <p className="text-xs font-bold uppercase tracking-[0.2em] text-stef">Archives</p>
                <h1 className="mt-2 font-heading text-2xl sm:text-3xl lg:text-4xl font-black tracking-tight text-slate-900">Historique</h1>
                <p className="mt-2 text-sm sm:text-base text-slate-600">Tous les dossiers, triés par jour.</p>
            </div>

            {/* Search bar */}
            <div className="mb-5 sm:mb-6 max-w-md relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400 pointer-events-none" />
                <input
                    data-testid="history-search"
                    value={query}
                    onChange={(e) => setQuery(e.target.value.toUpperCase())}
                    placeholder="Rechercher une plaque (ex : AB-123, CT-49…)"
                    autoCapitalize="characters"
                    autoCorrect="off"
                    spellCheck="false"
                    className="w-full h-11 rounded-md border border-slate-300 bg-white pl-10 pr-10 text-sm font-medium text-slate-900 placeholder:text-slate-400 placeholder:font-normal focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 transition uppercase"
                />
                {query && (
                    <button
                        data-testid="history-search-clear"
                        onClick={() => setQuery('')}
                        className="absolute right-2 top-1/2 -translate-y-1/2 h-7 w-7 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-500"
                        aria-label="Effacer"
                    >
                        <X className="h-4 w-4" />
                    </button>
                )}
            </div>

            {loading ? (
                <div className="text-slate-500">Chargement…</div>
            ) : folders.length === 0 ? (
                <div className="rounded-lg border border-dashed border-slate-300 bg-white p-12 text-center">
                    <HistoryIcon className="mx-auto h-8 w-8 text-slate-300" />
                    <p className="mt-3 font-heading font-bold text-slate-700">Aucun dossier dans l'historique</p>
                </div>
            ) : filtered.length === 0 ? (
                <div className="rounded-lg border border-dashed border-slate-300 bg-white p-12 text-center">
                    <Search className="mx-auto h-8 w-8 text-slate-300" />
                    <p className="mt-3 font-heading font-bold text-slate-700">Aucun résultat pour « {query} »</p>
                    <p className="mt-1 text-sm text-slate-500">Essaie une recherche plus large.</p>
                </div>
            ) : (
                <>
                    <p className="text-xs text-slate-500 mb-3" data-testid="history-result-count">
                        {filtered.length} dossier{filtered.length > 1 ? 's' : ''}{query ? ` pour « ${query} »` : ''} · affichés : {shown.length}
                    </p>
                    <div className="space-y-8" data-testid="history-groups">
                        {sortedKeys.map((k) => (
                            <div key={k}>
                                <div className="flex items-center gap-3 mb-3 flex-wrap">
                                    <span className="font-heading text-xs sm:text-sm font-bold uppercase tracking-[0.2em] text-stef">
                                        {new Date(k + 'T00:00:00').toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
                                    </span>
                                    <span className="text-xs text-slate-500">· {groups[k].length} dossier{groups[k].length > 1 ? 's' : ''}</span>
                                    <div className="flex-1 h-px bg-slate-200" />
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                    {groups[k].map((f) => (
                                        <div
                                            key={f.id}
                                            data-testid={`history-card-${f.id}`}
                                            onClick={() => navigate(`/folders/${f.id}`)}
                                            className="cursor-pointer rounded-lg border border-slate-200 bg-white p-4 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md hover:border-stef/40"
                                        >
                                            <div className="flex items-start gap-3">
                                                {f.preview ? (
                                                    <img src={f.preview} alt="" className="h-14 w-14 rounded-md object-cover border border-slate-200" />
                                                ) : (
                                                    <div className="h-14 w-14 rounded-md bg-slate-100 border border-slate-200 flex items-center justify-center">
                                                        <Truck className="h-5 w-5 text-slate-400" />
                                                    </div>
                                                )}
                                                <div className="flex-1 min-w-0">
                                                    <div className="flex items-center gap-2 flex-wrap">
                                                        <span className="font-heading font-black text-slate-900">{f.plate}</span>
                                                        <StatusBadge status={f.status} size="sm" />
                                                    </div>
                                                    <p className="mt-1 text-sm text-slate-600 line-clamp-1">{f.problem}</p>
                                                    <p className="mt-1 text-xs text-slate-500">{f.cariste_name} · {new Date(f.created_at).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })}</p>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))}
                    </div>

                    {hasMore && (
                        <div className="mt-8 text-center">
                            <button
                                data-testid="history-load-more"
                                onClick={() => setVisible((v) => v + PAGE_SIZE)}
                                className="inline-flex items-center gap-2 rounded-md border border-stef text-stef px-6 h-11 text-sm font-heading font-bold hover:bg-stef/5 transition-all"
                            >
                                Voir plus ({filtered.length - visible} restants)
                            </button>
                        </div>
                    )}
                </>
            )}
        </Layout>
    );
}
