'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
    Receipt, Search, Filter, Plus, FileText, ChevronLeft, ChevronRight,
    Loader2, Download, AlertCircle, RefreshCw
} from 'lucide-react';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';

export default function FacturasClient({ adminName }: { adminName: string }) {
    const router = useRouter();
    const [loading, setLoading] = useState(true);
    const [facturas, setFacturas] = useState<any[]>([]);
    const [total, setTotal] = useState(0);
    const [kpis, setKpis] = useState({ totalFacturado: 0, totalCobrado: 0, totalPendiente: 0 });

    // Paginación y Filtros
    const [page, setPage] = useState(1);
    const [search, setSearch] = useState('');
    const [estadoCobro, setEstadoCobro] = useState('');
    const limit = 20;

    const fetchFacturas = async () => {
        setLoading(true);
        try {
            const q = new URLSearchParams({
                page: page.toString(),
                limit: limit.toString(),
                search,
                estado: estadoCobro,
            });
            const res = await fetch(`/api/facturas?${q}`);
            if (res.ok) {
                const data = await res.json();
                setFacturas(data.facturas);
                setTotal(data.total);
                if (data.kpis) setKpis(data.kpis);
            }
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        const delayDebounceFn = setTimeout(() => {
            fetchFacturas();
        }, 400);
        return () => clearTimeout(delayDebounceFn);
    }, [page, search, estadoCobro]);

    const ESTADO_COLORS: Record<string, string> = {
        PENDIENTE: 'bg-red-100 text-red-700 border-red-200',
        COBRADA_PARCIAL: 'bg-amber-100 text-amber-700 border-amber-200',
        COBRADA_TOTAL: 'bg-green-100 text-green-700 border-green-200',
    };

    const ESTADO_LABELS: Record<string, string> = {
        PENDIENTE: 'Pendiente',
        COBRADA_PARCIAL: 'Cobro Parcial',
        COBRADA_TOTAL: 'Cobrada',
    };

    const formatCurrency = (val: number) => new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(val);

    return (
        <div className="space-y-6 pb-20">
            {/* HEADER */}
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight text-gray-900 flex items-center gap-2">
                        <Receipt className="w-7 h-7 text-[#1a365d]" />
                        Facturación
                    </h1>
                    <p className="text-sm text-gray-500 mt-1">
                        Gestión de facturas, seguimiento de cobros y emisión de documentos.
                    </p>
                </div>
            </div>

            {/* KPIS RAPIDOS */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center text-blue-600">
                        <FileText className="w-6 h-6" />
                    </div>
                    <div>
                        <p className="text-sm text-gray-500 font-medium">Total Facturado</p>
                        <p className="text-2xl font-bold text-gray-900">{formatCurrency(kpis.totalFacturado)}</p>
                    </div>
                </div>
                <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 rounded-full bg-green-50 flex items-center justify-center text-green-600">
                        <RefreshCw className="w-6 h-6" />
                    </div>
                    <div>
                        <p className="text-sm text-gray-500 font-medium">Total Cobrado</p>
                        <p className="text-2xl font-bold text-gray-900">{formatCurrency(kpis.totalCobrado)}</p>
                    </div>
                </div>
                <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-sm flex items-center gap-4">
                    <div className="w-12 h-12 rounded-full bg-red-50 flex items-center justify-center text-red-600">
                        <AlertCircle className="w-6 h-6" />
                    </div>
                    <div>
                        <p className="text-sm text-gray-500 font-medium">Pendiente de Cobro</p>
                        <p className="text-2xl font-bold text-red-600">{formatCurrency(kpis.totalPendiente)}</p>
                    </div>
                </div>
            </div>

            {/* FILTROS */}
            <div className="flex flex-col sm:flex-row gap-3">
                <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                        type="text"
                        placeholder="Buscar por Nº factura, cliente o CIF..."
                        value={search}
                        onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                        className="w-full pl-9 pr-4 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-[#1a365d]/20 outline-none"
                    />
                </div>
                <select
                    value={estadoCobro}
                    onChange={(e) => { setEstadoCobro(e.target.value); setPage(1); }}
                    className="border rounded-xl px-4 py-2 text-sm focus:ring-2 focus:ring-[#1a365d]/20 outline-none bg-white min-w-[180px]"
                >
                    <option value="">Todos los estados</option>
                    <option value="PENDIENTE">Pendientes</option>
                    <option value="COBRADA_PARCIAL">Cobro Parcial</option>
                    <option value="COBRADA_TOTAL">Cobradas (Total)</option>
                </select>
            </div>

            {/* TABLA DE RESULTADOS */}
            <div className="bg-white border rounded-2xl shadow-sm overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full text-left text-sm">
                        <thead className="bg-gray-50/80 border-b text-gray-600 font-medium">
                            <tr>
                                <th className="py-3 px-4">Factura Nº</th>
                                <th className="py-3 px-4">Fecha Emisión</th>
                                <th className="py-3 px-4">Cliente</th>
                                <th className="py-3 px-4">Importe Total</th>
                                <th className="py-3 px-4">Pendiente</th>
                                <th className="py-3 px-4">Estado Cobro</th>
                                <th className="py-3 px-4 text-right">Acciones</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100">
                            {loading && facturas.length === 0 ? (
                                <tr>
                                    <td colSpan={7} className="text-center py-12">
                                        <Loader2 className="w-6 h-6 animate-spin mx-auto text-gray-400" />
                                    </td>
                                </tr>
                            ) : facturas.length === 0 ? (
                                <tr>
                                    <td colSpan={7} className="text-center py-12 text-gray-500">
                                        No se encontraron facturas con estos filtros.
                                    </td>
                                </tr>
                            ) : (
                                facturas.map((f) => (
                                    <tr key={f.id} className="hover:bg-gray-50/50 transition-colors group">
                                        <td className="py-3 px-4 font-semibold text-[#1a365d]">{f.numero}</td>
                                        <td className="py-3 px-4 text-gray-600">
                                            {new Date(f.fechaEmision).toLocaleDateString('es-ES')}
                                        </td>
                                        <td className="py-3 px-4">
                                            <p className="font-medium text-gray-900">{f.clienteNombre}</p>
                                        </td>
                                        <td className="py-3 px-4 font-bold text-gray-900">
                                            {formatCurrency(f.total)}
                                        </td>
                                        <td className="py-3 px-4 font-medium text-red-600">
                                            {f.estadoCobro === 'COBRADA_TOTAL' ? '—' : formatCurrency(f.total - f.importeCobrado)}
                                        </td>
                                        <td className="py-3 px-4">
                                            <span className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-semibold border ${ESTADO_COLORS[f.estadoCobro]}`}>
                                                {ESTADO_LABELS[f.estadoCobro]}
                                            </span>
                                        </td>
                                        <td className="py-3 px-4 text-right">
                                            <Link
                                                href={`/dashboard/facturas/${f.id}`}
                                                className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-[#1a365d]/5 text-[#1a365d] hover:bg-[#1a365d]/10 rounded-lg transition-colors"
                                            >
                                                Gestionar
                                            </Link>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>

                {/* PAGINACIÓN */}
                {!loading && facturas.length > 0 && (
                    <div className="flex items-center justify-between px-6 py-4 border-t bg-gray-50/50">
                        <span className="text-sm text-gray-500">
                            Mostrando {facturas.length} de {total} {total === 1 ? 'resultado' : 'resultados'}
                        </span>
                        <div className="flex gap-2">
                            <button
                                onClick={() => setPage((p) => Math.max(1, p - 1))}
                                disabled={page === 1}
                                className="p-1.5 rounded-lg border bg-white text-gray-600 hover:bg-gray-50 disabled:opacity-50"
                            >
                                <ChevronLeft className="w-5 h-5" />
                            </button>
                            <button
                                onClick={() => setPage((p) => p + 1)}
                                disabled={page * limit >= total}
                                className="p-1.5 rounded-lg border bg-white text-gray-600 hover:bg-gray-50 disabled:opacity-50"
                            >
                                <ChevronRight className="w-5 h-5" />
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
