'use client';

import { useState, useEffect } from 'react';
import {
    BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend,
    LineChart, Line, CartesianGrid, AreaChart, Area, ComposedChart
} from 'recharts';
import { Download, Loader2, AlertCircle, TrendingUp, Users, Building2, Wrench, Search, RefreshCw, Filter } from 'lucide-react';
import * as XLSX from 'xlsx';
import { format, startOfMonth, subMonths } from 'date-fns';

const COLORS = ['#1a365d', '#3182ce', '#63b3ed', '#4fd1c5', '#38b2ac', '#e53e3e'];
const STATUS_COLORS: any = {
    'PENDIENTE': '#f6ad55',
    'EN PROCESO': '#63b3ed',
    'FINALIZADO': '#68d391',
    'CERRADO': '#48bb78',
    'CANCELADO': '#fc8181',
    'ACEPTADO': '#48bb78',
    'RECHAZADO': '#fc8181'
};

export default function EstadisticasClient() {
    const [data, setData] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    // Por defecto: Los últimos 6 meses
    const defaultStart = format(startOfMonth(subMonths(new Date(), 6)), 'yyyy-MM-dd');
    const defaultEnd = format(new Date(), 'yyyy-MM-dd');

    const [fechaInicio, setFechaInicio] = useState(defaultStart);
    const [fechaFin, setFechaFin] = useState(defaultEnd);

    const fetchEstadisticas = () => {
        setLoading(true);
        const queryParams = new URLSearchParams();
        if (fechaInicio) queryParams.append('fechaInicio', fechaInicio + "T00:00:00.000Z");
        if (fechaFin) queryParams.append('fechaFin', fechaFin + "T23:59:59.999Z");

        fetch(`/api/estadisticas?${queryParams.toString()}`)
            .then(res => res.json())
            .then(d => {
                if (d.error) throw new Error(d.error);
                setData(d);
            })
            .catch(err => setError(err.message))
            .finally(() => setLoading(false));
    };

    useEffect(() => {
        fetchEstadisticas();
    }, []); // eslint-disable-line react-hooks/exhaustive-deps

    const handleClearFilters = () => {
        setFechaInicio('');
        setFechaFin('');
        // Al vaciar los estados, usamos setTimeout para asegurar que el siguiente render dispara el fetch con valores vacios
        setTimeout(() => fetchEstadisticas(), 0);
    }

    const handleExportExcel = () => {
        if (!data) return;

        const wb = XLSX.utils.book_new();

        const filterTitle = (fechaInicio && !fechaFin) ? `Desde ${fechaInicio}` :
            (!fechaInicio && fechaFin) ? `Hasta ${fechaFin}` :
                (fechaInicio && fechaFin) ? `${fechaInicio} al ${fechaFin}` : 'Historico Global';

        // Hoja 1: Resumen Global
        const wsTotales = XLSX.utils.json_to_sheet([{
            'Filtro Aplicado': filterTitle,
            'Avisos Entrantes': data.totales.avisosTotales,
            'Partes de Trabajo': data.totales.partesTotales,
            'Total Facturado (€)': data.totales.totalFacturado,
            'Contratos Activos (Global)': data.totales.empresasContrato,
            'Usuarios Activos (Global)': data.totales.usuariosActivos,
        }]);
        XLSX.utils.book_append_sheet(wb, wsTotales, 'Resumen KPIs');

        // Hoja 2: Rendimiento Técnicos
        const wsRendimiento = XLSX.utils.json_to_sheet(data.rendimientoTecnicos.map((t: any) => ({
            'Usuario': t.name,
            'Avisos Cerrados': t.avisosCerrados,
            'Presupuestos Emitidos': t.presupuestos,
            'Suma Facturada (€)': t.facturado,
        })));
        XLSX.utils.book_append_sheet(wb, wsRendimiento, 'Rendimiento Usuarios');

        // Hoja 3: Evolución Histórica
        const wsEvolucion = XLSX.utils.json_to_sheet(data.evolucionAvisos.map((e: any) => ({
            'Fecha': e.fecha,
            'Avisos Nuevos': e.cantidad
        })));
        XLSX.utils.book_append_sheet(wb, wsEvolucion, 'Evolución Temporal');

        // Hoja 4: Rentabilidad Clientes (Incidencias)
        const wsIncidencias = XLSX.utils.json_to_sheet(data.incidenciasPorCliente.map((i: any) => ({
            'Cliente / Empresa': i.name,
            'Volumen Incidencias': i.cantidad
        })));
        XLSX.utils.book_append_sheet(wb, wsIncidencias, 'Incidencias Clientes');

        // Descargar Archivo
        const dateStr = new Date().toISOString().split('T')[0];
        XLSX.writeFile(wb, `BI_Climasan_${dateStr}.xlsx`);
    };

    if (error) return (
        <div className="p-6 bg-red-50 text-red-600 rounded-xl flex items-center gap-3">
            <AlertCircle className="w-6 h-6" />
            <p className="font-medium">Error cargando Dashboard: {error}</p>
        </div>
    );

    return (
        <div className="space-y-6 pb-20">
            {/* Cabecera y Barra de Controles Goblales */}
            <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-200 flex flex-col xl:flex-row justify-between xl:items-center gap-6">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 tracking-tight">Business Intelligence</h1>
                    <p className="text-gray-500 text-sm mt-1">
                        Analítica avanzada. Los datos representados varían según el rango de fechas seleccionado.
                    </p>
                </div>

                <div className="flex flex-col sm:flex-row items-end sm:items-center gap-3">
                    <div className="flex items-center gap-2 bg-gray-50 p-2 rounded-lg border border-gray-200 w-full sm:w-auto">
                        <Filter className="w-4 h-4 text-gray-400 ml-1" />
                        <div className="flex flex-col">
                            <span className="text-[10px] text-gray-500 font-semibold px-2">DESDE</span>
                            <input
                                type="date"
                                value={fechaInicio}
                                onChange={e => setFechaInicio(e.target.value)}
                                className="bg-transparent text-sm border-none outline-none cursor-pointer"
                            />
                        </div>
                        <div className="w-px h-8 bg-gray-300 mx-1"></div>
                        <div className="flex flex-col">
                            <span className="text-[10px] text-gray-500 font-semibold px-2">HASTA</span>
                            <input
                                type="date"
                                value={fechaFin}
                                onChange={e => setFechaFin(e.target.value)}
                                className="bg-transparent text-sm border-none outline-none cursor-pointer"
                            />
                        </div>
                    </div>

                    <div className="flex items-center gap-2 w-full sm:w-auto">
                        <button
                            onClick={fetchEstadisticas}
                            className="bg-[#1a365d] hover:bg-[#2a4a7f] text-white px-5 py-2.5 rounded-lg font-medium text-sm flex items-center gap-2 transition-colors w-full sm:w-auto justify-center"
                        >
                            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />} Analizar
                        </button>
                        <button
                            onClick={handleClearFilters}
                            className="bg-white hover:bg-gray-100 text-gray-600 border border-gray-300 px-3 py-2.5 rounded-lg flex items-center gap-2 transition-colors"
                            title="Limpiar fechas y ver todo el histórico"
                        >
                            <RefreshCw className="w-4 h-4" />
                        </button>
                    </div>

                    <div className="w-px h-10 bg-gray-200 hidden xl:block mx-2"></div>

                    <button
                        onClick={handleExportExcel}
                        disabled={loading || !data}
                        className="bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white px-5 py-2.5 rounded-lg font-medium text-sm flex items-center gap-2 transition-colors w-full sm:w-auto justify-center"
                    >
                        <Download className="w-4 h-4" /> Excel (.xlsx)
                    </button>
                </div>
            </div>

            {loading && !data ? (
                <div className="flex flex-col items-center justify-center py-20">
                    <Loader2 className="w-10 h-10 text-[#3182ce] animate-spin mb-4" />
                    <p className="text-gray-500 font-medium animate-pulse">Procesando volúmenes de datos...</p>
                </div>
            ) : data && (
                <>
                    {/* KPIs Dinámicos */}
                    <div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
                        <div className="bg-white p-4 rounded-xl border border-blue-100 border-l-4 border-l-blue-600 shadow-sm col-span-2 lg:col-span-1">
                            <p className="text-xs text-blue-600 font-bold uppercase tracking-wider mb-1">Mantenimientos Vivos</p>
                            <div className="flex items-center gap-2 text-3xl font-black text-gray-900">
                                {data.totales.empresasContrato} <Building2 className="w-5 h-5 text-gray-300 ml-auto" />
                            </div>
                        </div>

                        <div className="bg-white p-4 rounded-xl border border-red-100 border-l-4 border-l-red-500 shadow-sm">
                            <p className="text-xs text-red-600 font-bold uppercase tracking-wider mb-1">Avisos Recibidos</p>
                            <div className="flex items-center gap-2 text-3xl font-black text-gray-900">
                                {data.totales.avisosTotales} <AlertCircle className="w-5 h-5 text-gray-300 ml-auto" />
                            </div>
                        </div>

                        <div className="bg-white p-4 rounded-xl border border-amber-100 border-l-4 border-l-amber-500 shadow-sm">
                            <p className="text-xs text-amber-600 font-bold uppercase tracking-wider mb-1">Partes de Trabajo</p>
                            <div className="flex items-center gap-2 text-3xl font-black text-gray-900">
                                {data.totales.partesTotales} <Wrench className="w-5 h-5 text-gray-300 ml-auto" />
                            </div>
                        </div>

                        <div className="bg-white p-4 rounded-xl border border-emerald-100 border-l-4 border-l-emerald-600 shadow-sm col-span-2 lg:col-span-2">
                            <p className="text-xs text-emerald-600 font-bold uppercase tracking-wider mb-1">Impacto Económico</p>
                            <div className="flex items-center gap-2 text-3xl font-black text-gray-900">
                                {data.totales.totalFacturado.toLocaleString('es-ES', { minimumFractionDigits: 2 })} €
                                <span className="text-xs text-gray-400 font-medium ml-auto bg-gray-100 px-2 py-1 rounded">Facturado en el periodo</span>
                            </div>
                        </div>
                    </div>

                    {/* Fila 1 de Gráficos: Evolución temporal y Estados */}
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

                        {/* Evolución de Entradas */}
                        <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100 lg:col-span-2 relative">
                            <h3 className="text-sm font-bold text-gray-800 mb-6 flex items-center gap-2 uppercase tracking-wide">
                                <TrendingUp className="w-4 h-4 text-[#3182ce]" />
                                Cronología: Entradas de Incidencias
                            </h3>
                            {data.evolucionAvisos.length > 0 ? (
                                <div className="h-64 mt-2">
                                    <ResponsiveContainer width="100%" height="100%">
                                        <AreaChart data={data.evolucionAvisos} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                                            <defs>
                                                <linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
                                                    <stop offset="5%" stopColor="#3182ce" stopOpacity={0.8} />
                                                    <stop offset="95%" stopColor="#3182ce" stopOpacity={0} />
                                                </linearGradient>
                                            </defs>
                                            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#E2E8F0" />
                                            <XAxis dataKey="fecha" tick={{ fontSize: 10, fill: '#64748b' }} axisLine={false} tickLine={false} />
                                            <YAxis tick={{ fontSize: 11, fill: '#64748b' }} axisLine={false} tickLine={false} />
                                            <Tooltip contentStyle={{ borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }} />
                                            <Area type="monotone" dataKey="cantidad" stroke="#3182ce" strokeWidth={3} fillOpacity={1} fill="url(#colorUv)" />
                                        </AreaChart>
                                    </ResponsiveContainer>
                                </div>
                            ) : (
                                <p className="text-gray-400 text-sm text-center py-20">No hubo entradas en la fecha seleccionada.</p>
                            )}
                        </div>

                        {/* Comparador de Estados Partes y Presupuestos */}
                        <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100">
                            <h3 className="text-sm font-bold text-gray-800 mb-6 flex items-center gap-2 uppercase tracking-wide">
                                Estado de Trabajos
                            </h3>
                            <div className="space-y-4">
                                <div>
                                    <p className="text-xs font-semibold text-gray-500 mb-2">PARTES DE TRABAJO</p>
                                    {data.estadosPartes.length === 0 ? <p className="text-xs text-gray-400">Sin partes.</p> : (
                                        <div className="flex h-5 w-full rounded-full overflow-hidden">
                                            {data.estadosPartes.map((ep: any) => (
                                                <div
                                                    key={ep.name}
                                                    style={{ width: `${(ep.value / data.totales.partesTotales) * 100}%`, backgroundColor: STATUS_COLORS[ep.name] || '#cbd5e1' }}
                                                    title={`${ep.name}: ${ep.value}`}
                                                    className="h-full flex items-center justify-center text-[8px] font-bold text-white overflow-hidden transition-all hover:opacity-80"
                                                >
                                                    {((ep.value / data.totales.partesTotales) * 100) > 10 ? ep.value : ''}
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                    <div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
                                        {data.estadosPartes.map((ep: any) => (
                                            <div key={ep.name} className="flex items-center gap-1">
                                                <span className="w-2 h-2 rounded-full" style={{ backgroundColor: STATUS_COLORS[ep.name] || '#cbd5e1' }}></span>
                                                <span className="text-[10px] font-medium text-gray-600">{ep.name} ({ep.value})</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                                <div className="border-t border-gray-100 pt-4">
                                    <p className="text-xs font-semibold text-gray-500 mb-2">PRESUPUESTOS</p>
                                    {data.estadosPresupuestos.length === 0 ? <p className="text-xs text-gray-400">Sin presupuestos.</p> : (
                                        <div className="space-y-2">
                                            {data.estadosPresupuestos.map((ep: any) => (
                                                <div key={ep.name} className="flex items-center justify-between text-xs">
                                                    <div className="flex items-center gap-2">
                                                        <span className="w-2 h-2 rounded-full" style={{ backgroundColor: STATUS_COLORS[ep.name] || '#cbd5e1' }}></span>
                                                        <span className="font-medium text-gray-700">{ep.name}</span>
                                                    </div>
                                                    <span className="font-bold text-gray-900">{ep.value}</span>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>

                    </div>

                    {/* Fila 2: Rendimiento y Clientes */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

                        {/* Rendimiento por Técnico Mixto */}
                        <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100">
                            <h3 className="text-sm font-bold text-gray-800 mb-6 flex items-center gap-2 uppercase tracking-wide">
                                <Users className="w-4 h-4 text-[#38b2ac]" />
                                Productividad por Operario
                            </h3>
                            <div className="h-72">
                                <ResponsiveContainer width="100%" height="100%">
                                    <ComposedChart data={data.rendimientoTecnicos} margin={{ top: 20, right: 0, left: 0, bottom: 5 }}>
                                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                                        <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#64748b' }} axisLine={false} tickLine={false} />
                                        <YAxis yAxisId="left" tick={{ fontSize: 11, fill: '#64748b' }} axisLine={false} tickLine={false} />
                                        <YAxis yAxisId="right" orientation="right" tickFormatter={(v) => `€${v}`} tick={{ fontSize: 11, fill: '#38b2ac', fontWeight: 600 }} axisLine={false} tickLine={false} />
                                        <Tooltip
                                            cursor={{ fill: '#f8fafc' }}
                                            contentStyle={{ borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                                        />
                                        <Legend wrapperStyle={{ fontSize: '11px' }} />

                                        <Bar yAxisId="left" dataKey="avisosCerrados" name="Avisos Cerrados" fill="#3182ce" radius={[4, 4, 0, 0]} maxBarSize={40} />
                                        <Bar yAxisId="left" dataKey="presupuestos" name="Presupuestos Emitidos" fill="#63b3ed" radius={[4, 4, 0, 0]} maxBarSize={40} />

                                        {/* Línea superpuesta para la facturación para ver el impacto paralelo */}
                                        <Line yAxisId="right" type="monotone" dataKey="facturado" name="Ganancia Euro (€)" stroke="#38b2ac" strokeWidth={3} dot={{ r: 4, strokeWidth: 2 }} activeDot={{ r: 6 }} />
                                    </ComposedChart>
                                </ResponsiveContainer>
                            </div>
                        </div>

                        {/* Top Clientes con Incidencias */}
                        <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100">
                            <h3 className="text-sm font-bold text-gray-800 mb-6 flex items-center gap-2 uppercase tracking-wide">
                                <Building2 className="w-4 h-4 text-[#e53e3e]" />
                                Empresas Top Demandantes
                            </h3>
                            {data.incidenciasPorCliente.length > 0 ? (
                                <div className="h-72">
                                    <ResponsiveContainer width="100%" height="100%">
                                        <BarChart
                                            layout="vertical"
                                            data={data.incidenciasPorCliente}
                                            margin={{ top: 0, right: 20, left: -20, bottom: 0 }}
                                        >
                                            <CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#f1f5f9" />
                                            <XAxis type="number" tick={{ fontSize: 11, fill: '#64748b' }} axisLine={false} tickLine={false} />
                                            <YAxis type="category" dataKey="name" width={120} tick={{ fontSize: 10, fill: '#64748b' }} axisLine={false} tickLine={false} />
                                            <Tooltip
                                                cursor={{ fill: '#f8fafc' }}
                                                contentStyle={{ borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                                            />
                                            <Bar dataKey="cantidad" fill="#e53e3e" radius={[0, 4, 4, 0]} barSize={20} name="Total Avisos" background={{ fill: '#f8fafc' }} />
                                        </BarChart>
                                    </ResponsiveContainer>
                                </div>
                            ) : (
                                <p className="text-gray-400 text-sm text-center py-20">No hay datos suficientes</p>
                            )}
                        </div>

                    </div>
                </>
            )}
        </div>
    );
}
