<x-filament-panels::page>
<div class="space-y-6">

    {{-- ═══ PASO 1: UPLOAD ══════════════════════════════════════════════════════ --}}
    @if ($step === 'upload')

        <form wire:submit="analyze">
            {{ $this->form }}
            <div class="mt-4">
                <x-filament::button type="submit" wire:loading.attr="disabled" wire:target="analyze">
                    <span wire:loading.remove wire:target="analyze">Analizar CSV</span>
                    <span wire:loading wire:target="analyze">Analizando...</span>
                </x-filament::button>
            </div>
        </form>

        <x-filament::section>
            <x-slot name="heading">¿Cómo descargar el CSV?</x-slot>
            <ol class="list-decimal list-inside space-y-1 text-sm text-gray-600 dark:text-gray-400">
                <li>Upwork → <strong>Reports → Transaction History</strong></li>
                <li>Seleccionar el período deseado</li>
                <li>Clic en <strong>Export to CSV</strong></li>
                <li>El archivo se llama <code class="bg-gray-100 dark:bg-gray-800 px-1 rounded text-xs">transaction_report.csv</code></li>
            </ol>
            <p class="mt-2 text-xs text-gray-500 dark:text-gray-400">
                Se importan pagos (Hourly/Fixed-price) y retiros (Withdrawal). Las comisiones de Upwork (Service Fee) y la membresía se omiten.
                Por cada pago se crea automáticamente la <strong>Venta</strong> y el <strong>Cliente</strong> si no existen en Nuna.
            </p>
        </x-filament::section>

    {{-- ═══ PASO 2: PREVIEW ═════════════════════════════════════════════════════ --}}
    @elseif ($step === 'preview')

        {{-- Resumen de análisis --}}
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div class="rounded-xl bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 p-4 text-center">
                <div class="text-3xl font-bold text-green-700 dark:text-green-300">{{ count($previewNew) }}</div>
                <div class="text-sm font-medium text-green-600 dark:text-green-400 mt-1">Registros nuevos</div>
            </div>
            <div class="rounded-xl bg-amber-50 dark:bg-amber-950 border border-amber-200 dark:border-amber-800 p-4 text-center">
                <div class="text-3xl font-bold text-amber-700 dark:text-amber-300">{{ count($previewDups) }}</div>
                <div class="text-sm font-medium text-amber-600 dark:text-amber-400 mt-1">Duplicados (ya existen)</div>
            </div>
            <div class="rounded-xl bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 p-4 text-center">
                <div class="text-3xl font-bold text-red-700 dark:text-red-300">{{ count($previewInvalid) }}</div>
                <div class="text-sm font-medium text-red-600 dark:text-red-400 mt-1">Inválidos / sin ID</div>
            </div>
        </div>

        {{-- Tabla: Registros NUEVOS --}}
        @if (count($previewNew) > 0)
            <x-filament::section>
                <x-slot name="heading">
                    <span class="text-green-700 dark:text-green-400">Registros a importar ({{ count($previewNew) }})</span>
                </x-slot>
                <div class="overflow-x-auto">
                    <table class="min-w-full text-sm divide-y divide-gray-200 dark:divide-gray-700">
                        <thead>
                            <tr class="text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                <th class="py-2 pr-4">Fecha pago</th>
                                <th class="py-2 pr-4">Tipo</th>
                                <th class="py-2 pr-4">Contrato / Destino</th>
                                <th class="py-2 pr-4">Cliente</th>
                                <th class="py-2 text-right">Monto</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                            @foreach ($previewNew as $row)
                                <tr class="hover:bg-green-50 dark:hover:bg-green-950/30">
                                    <td class="py-2 pr-4 whitespace-nowrap text-gray-700 dark:text-gray-300 text-xs">
                                        {{ \Carbon\Carbon::parse($row['transaction_date'])->format('d/m/Y') }}
                                        @if ($row['date_from'] !== $row['transaction_date'])
                                            <div class="text-gray-400">{{ \Carbon\Carbon::parse($row['date_from'])->format('d/m') }} → {{ \Carbon\Carbon::parse($row['date_to'])->format('d/m') }}</div>
                                        @endif
                                    </td>
                                    <td class="py-2 pr-4">
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium
                                            {{ in_array($row['payment_type'], ['Hourly','Fixed-price','Fixed Price']) ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200' }}">
                                            {{ $row['payment_type'] }}
                                        </span>
                                    </td>
                                    <td class="py-2 pr-4 text-gray-900 dark:text-white font-medium text-sm">
                                        {{ $row['contract_title'] }}
                                    </td>
                                    <td class="py-2 pr-4 text-gray-500 dark:text-gray-400 text-sm">
                                        {{ $row['client_name'] ?: '—' }}
                                    </td>
                                    <td class="py-2 text-right font-semibold {{ $row['amount'] >= 0 ? 'text-green-700 dark:text-green-400' : 'text-red-600 dark:text-red-400' }}">
                                        ${{ number_format($row['amount'], 2) }}
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                        <tfoot>
                            <tr class="border-t-2 border-green-200 dark:border-green-800">
                                <td colspan="3" class="py-2 pr-4 text-right font-semibold text-gray-700 dark:text-gray-300">Total:</td>
                                <td class="py-2 text-right font-bold text-green-700 dark:text-green-400">
                                    ${{ number_format(array_sum(array_column($previewNew, 'amount')), 2) }}
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </x-filament::section>
        @endif

        {{-- Tabla: DUPLICADOS --}}
        @if (count($previewDups) > 0)
            <x-filament::section>
                <x-slot name="heading">
                    <span class="text-amber-700 dark:text-amber-400">Ya existen en el sistema ({{ count($previewDups) }}) — se omitirán</span>
                </x-slot>
                <div class="overflow-x-auto">
                    <table class="min-w-full text-sm divide-y divide-gray-200 dark:divide-gray-700">
                        <thead>
                            <tr class="text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                <th class="py-2 pr-4">Fecha pago</th>
                                <th class="py-2 pr-4">Tipo</th>
                                <th class="py-2 pr-4">Contrato / Destino</th>
                                <th class="py-2 text-right">Monto</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                            @foreach ($previewDups as $row)
                                <tr class="opacity-60">
                                    <td class="py-2 pr-4 whitespace-nowrap text-gray-500 dark:text-gray-400 text-xs">
                                        {{ \Carbon\Carbon::parse($row['transaction_date'])->format('d/m/Y') }}
                                    </td>
                                    <td class="py-2 pr-4 text-gray-400 text-xs">{{ $row['payment_type'] }}</td>
                                    <td class="py-2 pr-4 text-gray-500 dark:text-gray-400">{{ $row['contract_title'] }}</td>
                                    <td class="py-2 text-right text-gray-500 dark:text-gray-400">
                                        ${{ number_format($row['amount'], 2) }}
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </x-filament::section>
        @endif

        {{-- Inválidos --}}
        @if (count($previewInvalid) > 0)
            <x-filament::section>
                <x-slot name="heading">
                    <span class="text-red-700 dark:text-red-400">Filas inválidas ({{ count($previewInvalid) }}) — se ignorarán</span>
                </x-slot>
                <ul class="text-sm text-red-600 dark:text-red-400 space-y-1">
                    @foreach ($previewInvalid as $inv)
                        <li>
                            Línea {{ $inv['line'] ?? '?' }}:
                            {{ $inv['error'] ?? $inv['raw'] ?? 'desconocido' }}
                        </li>
                    @endforeach
                </ul>
            </x-filament::section>
        @endif

        {{-- Aviso si no hay nada nuevo --}}
        @if (count($previewNew) === 0)
            <x-filament::section>
                <p class="text-sm text-amber-700 dark:text-amber-400 font-medium">
                    No hay registros nuevos para importar. Todos los pagos del archivo ya existen en el sistema.
                </p>
            </x-filament::section>
        @endif

        {{-- Botones de acción --}}
        <div class="flex items-center gap-4">
            @if (count($previewNew) > 0)
                <x-filament::button wire:click="confirmImport" wire:loading.attr="disabled" wire:target="confirmImport" color="success">
                    <span wire:loading.remove wire:target="confirmImport">
                        Confirmar e importar {{ count($previewNew) }} registro(s)
                    </span>
                    <span wire:loading wire:target="confirmImport">Importando...</span>
                </x-filament::button>
            @endif

            <x-filament::button wire:click="resetWizard" color="gray" outlined>
                Cancelar y volver
            </x-filament::button>
        </div>

    {{-- ═══ PASO 3: DONE ════════════════════════════════════════════════════════ --}}
    @elseif ($step === 'done')

        <x-filament::section>
            <x-slot name="heading">Importación completada</x-slot>
            <div class="space-y-4">
                <p class="text-sm text-gray-600 dark:text-gray-400">
                    Los pagos han sido registrados correctamente en el sistema.
                </p>
                <div class="flex items-center gap-4">
                    <x-filament::button
                        tag="a"
                        :href="route('filament.admin.resources.upwork-earnings.index')"
                        color="primary"
                    >
                        Ver pagos importados
                    </x-filament::button>
                    <x-filament::button wire:click="resetWizard" color="gray" outlined>
                        Importar otro archivo
                    </x-filament::button>
                </div>
            </div>
        </x-filament::section>

    @endif

</div>

<x-filament-actions::modals />
</x-filament-panels::page>
