<x-filament-panels::page>

    {{-- ── Barra de filtros ────────────────────────────────────────────────── --}}
    <div class="flex flex-wrap items-end gap-3 mb-6">

        {{-- Presets --}}
        <div class="flex gap-1">
            @foreach(['month' => 'Este mes', 'lastmonth' => 'Mes pasado', 'months3' => 'Últ. 3 meses'] as $key => $label)
                <button wire:click="setPreset('{{ $key }}')"
                    class="px-3 py-1.5 rounded-lg text-sm font-medium transition-colors
                        {{ $preset === $key
                            ? 'bg-primary-600 text-white'
                            : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 hover:bg-gray-50' }}">
                    {{ $label }}
                </button>
            @endforeach
        </div>

        {{-- Desde / Hasta --}}
        <div class="flex items-center gap-2">
            <input type="date" wire:model.live="desde"
                class="rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white text-sm px-3 py-1.5">
            <span class="text-gray-400 text-sm">—</span>
            <input type="date" wire:model.live="hasta"
                class="rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white text-sm px-3 py-1.5">
        </div>

        {{-- Export --}}
        <a href="{{ $this->getExportUrl() }}" target="_blank"
            class="ml-auto inline-flex items-center gap-1.5 px-4 py-1.5 rounded-lg bg-success-600 hover:bg-success-700 text-white text-sm font-medium transition-colors">
            <x-heroicon-o-arrow-down-tray class="w-4 h-4"/>
            Exportar Excel
        </a>
    </div>

    @php $data = $this->getReportData(); @endphp

    {{-- ── KPI Cards ──────────────────────────────────────────────────────── --}}
    <div style="display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:1rem; margin-bottom:1.5rem;">

        <div class="rounded-xl bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-4 shadow-sm">
            <p class="text-xs font-semibold text-red-400 uppercase tracking-wide">Total Pendiente</p>
            <p class="text-2xl font-bold text-red-600 dark:text-red-400 mt-1">
                Bs. {{ number_format($data['totalPendingBs'], 2) }}
            </p>
            <p class="text-xs text-red-400 mt-0.5">{{ $data['pending']->count() }} cuentas abiertas</p>
        </div>

        <div class="rounded-xl bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 p-4 shadow-sm">
            <p class="text-xs font-semibold text-orange-400 uppercase tracking-wide">Total Vencido</p>
            <p class="text-2xl font-bold text-orange-600 dark:text-orange-400 mt-1">
                Bs. {{ number_format($data['totalOverdueBs'], 2) }}
            </p>
            <p class="text-xs text-orange-400 mt-0.5">Pasada la F. Cobro</p>
        </div>

        <div class="rounded-xl bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-4 shadow-sm">
            <p class="text-xs font-semibold text-green-500 uppercase tracking-wide">Cobrado en período</p>
            <p class="text-2xl font-bold text-green-600 dark:text-green-400 mt-1">
                Bs. {{ number_format($data['collectedInPeriodBs'], 2) }}
            </p>
            <p class="text-xs text-green-400 mt-0.5">
                {{ \Carbon\Carbon::parse($data['desde'])->format('d/m') }} —
                {{ \Carbon\Carbon::parse($data['hasta'])->format('d/m/Y') }}
            </p>
        </div>

        <div class="rounded-xl bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-4 shadow-sm">
            <p class="text-xs font-semibold text-blue-400 uppercase tracking-wide">Promedio días cobro</p>
            <p class="text-2xl font-bold text-blue-600 dark:text-blue-400 mt-1">
                {{ $data['avgDays'] ? $data['avgDays'].' días' : '—' }}
            </p>
            <p class="text-xs text-blue-400 mt-0.5">Desde creación → cobro</p>
        </div>
    </div>

    {{-- ── Aging Buckets ───────────────────────────────────────────────────── --}}
    <div style="display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); gap:0.75rem; margin-bottom:1.5rem;">
        @foreach($data['aging'] as $key => $bucket)
            <div class="rounded-lg border p-3 text-center
                {{ $bucket['color'] === 'success' ? 'border-green-200 bg-green-50 dark:bg-green-900/20' : '' }}
                {{ $bucket['color'] === 'warning' ? 'border-yellow-200 bg-yellow-50 dark:bg-yellow-900/20' : '' }}
                {{ $bucket['color'] === 'danger'  ? 'border-red-200 bg-red-50 dark:bg-red-900/20' : '' }}
                {{ $bucket['color'] === 'gray'    ? 'border-gray-200 bg-gray-50 dark:bg-gray-800' : '' }}">
                <p class="text-xs font-semibold
                    {{ $bucket['color'] === 'success' ? 'text-green-600' : '' }}
                    {{ $bucket['color'] === 'warning' ? 'text-yellow-600' : '' }}
                    {{ $bucket['color'] === 'danger'  ? 'text-red-600' : '' }}
                    {{ $bucket['color'] === 'gray'    ? 'text-gray-500' : '' }}">
                    {{ $bucket['label'] }}
                </p>
                <p class="text-xl font-bold mt-1
                    {{ $bucket['color'] === 'success' ? 'text-green-700' : '' }}
                    {{ $bucket['color'] === 'warning' ? 'text-yellow-700' : '' }}
                    {{ $bucket['color'] === 'danger'  ? 'text-red-700' : '' }}
                    {{ $bucket['color'] === 'gray'    ? 'text-gray-600' : '' }}">
                    {{ $bucket['count'] }}
                </p>
                @if($bucket['totalBs'] > 0)
                    <p class="text-xs mt-0.5
                        {{ $bucket['color'] === 'success' ? 'text-green-500' : '' }}
                        {{ $bucket['color'] === 'warning' ? 'text-yellow-500' : '' }}
                        {{ $bucket['color'] === 'danger'  ? 'text-red-500' : '' }}
                        {{ $bucket['color'] === 'gray'    ? 'text-gray-400' : '' }}">
                        Bs. {{ number_format($bucket['totalBs'], 2) }}
                    </p>
                @endif
            </div>
        @endforeach
    </div>

    {{-- ── Tabla de CxC Pendientes ─────────────────────────────────────────── --}}
    <x-filament::section class="mb-4">
        <x-slot name="heading">
            <span class="text-base font-semibold text-red-600 dark:text-red-400">
                ⏳ Cuentas pendientes de cobro ({{ $data['pending']->count() }})
            </span>
        </x-slot>

        @if($data['pending']->isEmpty())
            <p class="text-center text-gray-400 py-8">¡Sin cuentas pendientes! 🎉</p>
        @else
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-gray-200 dark:border-gray-700">
                            <th class="text-left py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Cliente</th>
                            <th class="text-left py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Venta</th>
                            <th class="text-center py-2 px-3 text-xs font-semibold text-gray-500 uppercase">F.Venta</th>
                            <th class="text-center py-2 px-3 text-xs font-semibold text-gray-500 uppercase">F.Cobro</th>
                            <th class="text-center py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Días</th>
                            <th class="text-center py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Mon.</th>
                            <th class="text-right py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Neto</th>
                            <th class="text-right py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Cobrado</th>
                            <th class="text-right py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Saldo</th>
                            <th class="text-center py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Estado</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($data['pending'] as $sale)
                            @php
                                $hasDate   = (bool) $sale->expected_collect_date;
                                $isPast    = $hasDate && $sale->expected_collect_date->isPast();
                                $daysOver  = $isPast ? (int) now()->diffInDays($sale->expected_collect_date) : 0;
                                $rowColor  = match(true) {
                                    $daysOver > 60 => 'bg-red-50 dark:bg-red-900/10',
                                    $daysOver > 30 => 'bg-orange-50 dark:bg-orange-900/10',
                                    $daysOver > 0  => 'bg-yellow-50 dark:bg-yellow-900/10',
                                    default        => '',
                                };
                            @endphp
                            <tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50 {{ $rowColor }}">
                                <td class="py-2 px-3 font-medium text-gray-900 dark:text-white">{{ $sale->client?->name }}</td>
                                <td class="py-2 px-3 text-gray-600 dark:text-gray-300 max-w-xs truncate" title="{{ $sale->title }}">{{ $sale->title }}</td>
                                <td class="py-2 px-3 text-center text-gray-500 whitespace-nowrap">{{ $sale->sale_date?->format('d/m/Y') }}</td>
                                <td class="py-2 px-3 text-center whitespace-nowrap
                                    {{ $isPast ? 'text-red-600 font-semibold' : 'text-gray-500' }}">
                                    {{ $hasDate ? $sale->expected_collect_date->format('d/m/Y') : '—' }}
                                </td>
                                <td class="py-2 px-3 text-center">
                                    @if($daysOver > 0)
                                        <span class="inline-flex px-1.5 py-0.5 rounded text-xs font-bold
                                            {{ $daysOver > 60 ? 'bg-red-100 text-red-700' : ($daysOver > 30 ? 'bg-orange-100 text-orange-700' : 'bg-yellow-100 text-yellow-700') }}">
                                            +{{ $daysOver }}d
                                        </span>
                                    @elseif($hasDate && !$isPast)
                                        <span class="text-green-500 text-xs">Al día</span>
                                    @else
                                        <span class="text-gray-400 text-xs">—</span>
                                    @endif
                                </td>
                                <td class="py-2 px-3 text-center">
                                    <span class="inline-flex px-1.5 py-0.5 rounded text-xs font-semibold
                                        {{ $sale->currency === \App\Enums\Currency::USD ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700' }}">
                                        {{ $sale->currency?->value }}
                                    </span>
                                </td>
                                <td class="py-2 px-3 text-right font-mono text-gray-700 dark:text-gray-300">
                                    {{ $sale->currency?->symbol() }}{{ number_format($sale->net_expected, 2) }}
                                </td>
                                <td class="py-2 px-3 text-right font-mono text-green-600">
                                    {{ $sale->collected_amount_cached > 0 ? $sale->currency?->symbol().number_format((float)$sale->collected_amount_cached,2) : '—' }}
                                </td>
                                <td class="py-2 px-3 text-right font-mono font-bold text-red-600">
                                    {{ $sale->currency?->symbol() }}{{ number_format($sale->balance, 2) }}
                                </td>
                                <td class="py-2 px-3 text-center">
                                    @php $st = $sale->payment_status; @endphp
                                    <span class="inline-flex px-2 py-0.5 rounded-full text-xs font-medium
                                        {{ $st === \App\Enums\PaymentStatus::Partial ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700' }}">
                                        {{ $st?->label() }}
                                    </span>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot>
                        <tr class="border-t-2 border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-800/60 font-semibold">
                            <td colspan="8" class="py-2 px-3 text-right text-xs uppercase text-gray-500">Total pendiente (Bs. equiv.)</td>
                            <td class="py-2 px-3 text-right font-mono text-red-600 text-base">
                                Bs. {{ number_format($data['totalPendingBs'], 2) }}
                            </td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        @endif
    </x-filament::section>

    {{-- ── Tabla de cobradas en período ───────────────────────────────────── --}}
    <x-filament::section collapsible collapsed>
        <x-slot name="heading">
            <span class="text-base font-semibold text-green-600 dark:text-green-400">
                ✅ Cobradas en el período
                ({{ $data['paidInPeriod']->count() }} ventas — Bs. {{ number_format($data['collectedInPeriodBs'], 2) }})
            </span>
        </x-slot>

        @if($data['paidInPeriod']->isEmpty())
            <p class="text-center text-gray-400 py-6">No hay ventas cobradas en este período.</p>
        @else
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-gray-200 dark:border-gray-700">
                            <th class="text-left py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Cliente</th>
                            <th class="text-left py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Venta</th>
                            <th class="text-center py-2 px-3 text-xs font-semibold text-gray-500 uppercase">F.Pago</th>
                            <th class="text-center py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Mon.</th>
                            <th class="text-right py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Bruto</th>
                            <th class="text-right py-2 px-3 text-xs font-semibold text-gray-500 uppercase">Neto cobrado</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($data['paidInPeriod'] as $sale)
                            @php
                                $lastPayment = $sale->payments->sortByDesc('payment_date')->first();
                            @endphp
                            <tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50">
                                <td class="py-2 px-3 font-medium text-gray-900 dark:text-white">{{ $sale->client?->name }}</td>
                                <td class="py-2 px-3 text-gray-600 dark:text-gray-300 max-w-xs truncate">{{ $sale->title }}</td>
                                <td class="py-2 px-3 text-center text-gray-500">{{ $lastPayment?->payment_date?->format('d/m/Y') ?? '—' }}</td>
                                <td class="py-2 px-3 text-center">
                                    <span class="inline-flex px-1.5 py-0.5 rounded text-xs font-semibold
                                        {{ $sale->currency === \App\Enums\Currency::USD ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700' }}">
                                        {{ $sale->currency?->value }}
                                    </span>
                                </td>
                                <td class="py-2 px-3 text-right font-mono text-gray-500">
                                    {{ $sale->currency?->symbol() }}{{ number_format((float)$sale->gross_amount, 2) }}
                                </td>
                                <td class="py-2 px-3 text-right font-mono font-semibold text-green-600">
                                    {{ $sale->currency?->symbol() }}{{ number_format((float)$sale->collected_amount_cached, 2) }}
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </x-filament::section>

</x-filament-panels::page>
