<?php

declare(strict_types=1);

namespace App\Filament\Resources\Payments\Schemas;

use App\Filament\Resources\Clients\ClientResource;
use App\Filament\Resources\Credits\CreditResource;
use App\Filament\Resources\Payments\PaymentResource;
use App\Models\Payment;
use App\Models\User;
use App\Support\Format;
use Carbon\Carbon;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Schema;
use Filament\Support\Enums\FontWeight;
use Filament\Support\Enums\TextSize;

class PaymentInfolist
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->columns(1)
            ->inlineLabel(false)
            ->components([
                // ═══════════════════════════════════════════════════════════════════════
                // 1. HERO SECTION: Estado del Pago
                // ═══════════════════════════════════════════════════════════════════════
                Section::make()
                    ->schema([
                        TextEntry::make('status_hero')
                            ->label('')
                            ->hiddenLabel()
                            ->state(fn (Payment $record) => $record->voided ? 'ANULADO' : 'ACTIVO')
                            ->badge()
                            ->color(fn (Payment $record) => $record->voided ? 'danger' : 'success')
                            ->size(TextSize::Large)
                            ->weight(FontWeight::Bold)
                            ->icon(fn (Payment $record) => $record->voided
                                ? 'heroicon-o-x-circle'
                                : 'heroicon-o-check-circle')
                            ->columnSpan(1),

                        TextEntry::make('context_indicator')
                            ->label('')
                            ->hiddenLabel()
                            ->state(function (Payment $record): string {
                                if ($record->voided) {
                                    $reason = $record->void_reason ?: 'Sin motivo especificado';
                                    $user = $record->voided_by_user_id
                                        ? User::find($record->voided_by_user_id)?->name ?? 'Usuario desconocido'
                                        : 'Usuario desconocido';
                                    $date = $record->voided_at
                                        ? Carbon::parse($record->voided_at)->format('d/m/Y H:i')
                                        : 'Fecha no registrada';

                                    return "Motivo: {$reason} · Por: {$user} · {$date}";
                                }

                                $count = $record->installments()->count();

                                if ($count === 0) {
                                    return 'Pago sin distribución registrada';
                                }

                                return $count === 1
                                    ? 'Pago aplicado a 1 cuota'
                                    : "Pago distribuido en {$count} cuotas";
                            })
                            ->icon(fn (Payment $record) => $record->voided
                                ? 'heroicon-o-exclamation-triangle'
                                : 'heroicon-o-information-circle')
                            ->color(fn (Payment $record) => $record->voided ? 'danger' : 'gray')
                            ->columnSpan(3),
                    ])
                    ->columns(4)
                    ->extraAttributes(['class' => 'mb-2']),

                // ═══════════════════════════════════════════════════════════════════════
                // 2. KPI CARDS: Resumen Financiero
                // ═══════════════════════════════════════════════════════════════════════
                Section::make('Resumen Financiero')
                    ->description('Montos del pago')
                    ->icon('heroicon-o-chart-bar')
                    ->collapsible()
                    ->schema([
                        TextEntry::make('amount')
                            ->label('MONTO TOTAL')
                            ->formatStateUsing(fn ($state) => Format::money($state))
                            ->size(TextSize::Large)
                            ->weight(FontWeight::Bold)
                            ->color('info')
                            ->icon('heroicon-o-banknotes'),

                        TextEntry::make('applied_amount')
                            ->label('MONTO APLICADO')
                            ->formatStateUsing(fn ($state) => Format::money($state))
                            ->size(TextSize::Large)
                            ->weight(FontWeight::Bold)
                            ->color('success')
                            ->icon('heroicon-o-check-circle'),

                        TextEntry::make('extra_amount')
                            ->label('EXCEDENTE')
                            ->formatStateUsing(fn ($state) => Format::money($state))
                            ->size(TextSize::Large)
                            ->weight(FontWeight::Bold)
                            ->color(fn (Payment $record) => (float) $record->extra_amount > 0 ? 'warning' : 'gray')
                            ->icon('heroicon-o-arrow-trending-up'),

                        TextEntry::make('payment_method')
                            ->label('MÉTODO DE PAGO')
                            ->badge()
                            ->formatStateUsing(fn (?string $state) => match ($state) {
                                'cash' => 'Efectivo',
                                'transfer' => 'Transferencia',
                                'nequi' => 'Nequi',
                                'daviplata' => 'Daviplata',
                                'card' => 'Tarjeta',
                                'check' => 'Cheque',
                                default => $state ? ucfirst($state) : '-',
                            })
                            ->color('gray')
                            ->icon('heroicon-o-credit-card')
                            ->size(TextSize::Large)
                            ->weight(FontWeight::Bold),
                    ])
                    ->columns(4),

                // ═══════════════════════════════════════════════════════════════════════
                // 3. CRÉDITO ASOCIADO
                // ═══════════════════════════════════════════════════════════════════════
                Section::make('Crédito Asociado')
                    ->description('Estado del crédito vinculado')
                    ->icon('heroicon-o-credit-card')
                    ->collapsible()
                    ->collapsed(false)
                    ->visible(fn (Payment $record) => $record->credit_id !== null)
                    ->schema([
                        TextEntry::make('credit.status')
                            ->label('Estado del Crédito')
                            ->badge()
                            ->formatStateUsing(fn ($state, Payment $record) => $record->credit?->getStatusLabel() ?? '-')
                            ->color(fn (Payment $record) => $record->credit?->getStatusBadgeColor() ?? 'gray'),

                        TextEntry::make('credit.remaining_balance')
                            ->label('Saldo Pendiente')
                            ->formatStateUsing(fn ($state, Payment $record) => Format::money($record->credit?->remaining_balance ?? 0))
                            ->icon('heroicon-o-currency-dollar')
                            ->weight(FontWeight::Bold)
                            ->color('danger'),

                        TextEntry::make('credit_progress')
                            ->label('Progreso de Cuotas')
                            ->state(function (Payment $record): string {
                                $credit = $record->credit;
                                if (! $credit) {
                                    return '-';
                                }
                                $paid = $credit->installments_paid_count;
                                $total = $credit->installments_count;

                                return "{$paid} / {$total} pagadas";
                            })
                            ->icon('heroicon-o-chart-bar-square'),

                        TextEntry::make('credit.id')
                            ->label('Ver Crédito')
                            ->badge()
                            ->color('info')
                            ->formatStateUsing(fn ($state) => "Crédito #{$state}")
                            ->url(fn (Payment $record) => $record->credit_id
                                ? CreditResource::getUrl('view', ['record' => $record->credit_id])
                                : null
                            ),
                    ])
                    ->columns(4),

                // ═══════════════════════════════════════════════════════════════════════
                // 4. DETALLE DEL PAGO
                // ═══════════════════════════════════════════════════════════════════════
                Section::make('Detalle del Pago')
                    ->description('Quién, cuándo y cómo')
                    ->icon('heroicon-o-document-text')
                    ->collapsible()
                    ->collapsed(false)
                    ->schema([
                        TextEntry::make('credit.client.name')
                            ->label('Cliente')
                            ->icon('heroicon-m-user')
                            ->weight(FontWeight::Medium)
                            ->url(fn (Payment $record) => $record->credit?->client
                                ? ClientResource::getUrl('view', ['record' => $record->credit->client])
                                : null
                            ),

                        TextEntry::make('credit.collector.name')
                            ->label('Cobrador')
                            ->icon('heroicon-m-user-circle')
                            ->placeholder('Sin cobrador'),

                        TextEntry::make('installment.installment_number')
                            ->label('Cuota Preferida')
                            ->badge()
                            ->formatStateUsing(fn ($state) => $state
                                ? "Cuota #{$state}"
                                : '-'
                            )
                            ->color(fn (Payment $record) => $record->installment
                                ? $record->installment->getStatusBadgeColor()
                                : 'gray'
                            )
                            ->placeholder('-'),

                        TextEntry::make('registeredBy.name')
                            ->label('Registrado por')
                            ->icon('heroicon-m-user-circle')
                            ->placeholder('No registrado'),

                        TextEntry::make('payment_date')
                            ->label('Fecha de Pago')
                            ->icon('heroicon-o-calendar')
                            ->formatStateUsing(function ($state): string {
                                if (! $state) {
                                    return '-';
                                }
                                $date = Carbon::parse($state);

                                return $date->format('d/m/Y').' ('.$date->diffForHumans().')';
                            }),

                        TextEntry::make('created_at')
                            ->label('Fecha de Registro')
                            ->icon('heroicon-o-clock')
                            ->dateTime('d/m/Y H:i'),
                    ])
                    ->columns(3),

                // ═══════════════════════════════════════════════════════════════════════
                // 5. TABS: Distribución y Auditoría
                // ═══════════════════════════════════════════════════════════════════════
                Tabs::make('payment_details')
                    ->columnSpanFull()
                    ->tabs([
                        Tab::make('Distribución')
                            ->icon('heroicon-m-table-cells')
                            ->badge(fn (Payment $record) => $record->installments()->count() ?: null)
                            ->badgeColor('info')
                            ->schema([
                                ViewEntry::make('distribution_table')
                                    ->view('filament.infolists.components.payment-distribution-table')
                                    ->columnSpanFull(),
                            ]),

                        Tab::make('Auditoría')
                            ->icon('heroicon-m-clipboard-document-list')
                            ->badge(fn (Payment $record) => $record->auditLogs()->count() ?: null)
                            ->badgeColor('gray')
                            ->schema([
                                ViewEntry::make('audit_timeline')
                                    ->view('filament.infolists.components.payment-audit-timeline')
                                    ->columnSpanFull(),
                            ]),
                    ]),

                // ═══════════════════════════════════════════════════════════════════════
                // 6. TECHNICAL INFO: Collapsed by Default
                // ═══════════════════════════════════════════════════════════════════════
                Section::make('Información Técnica')
                    ->description('Datos técnicos y de auditoría')
                    ->icon('heroicon-o-cog-6-tooth')
                    ->collapsible()
                    ->collapsed()
                    ->schema([
                        TextEntry::make('id')
                            ->label('ID del Pago')
                            ->badge()
                            ->color('gray'),

                        TextEntry::make('original_payment_id')
                            ->label('Pago Original')
                            ->placeholder('Ninguno')
                            ->url(fn (Payment $record) => $record->original_payment_id
                                ? PaymentResource::getUrl('view', ['record' => $record->original_payment_id])
                                : null
                            ),

                        TextEntry::make('idempotency_key')
                            ->label('Clave de Idempotencia')
                            ->placeholder('-')
                            ->copyable(),

                        TextEntry::make('device_id')
                            ->label('ID de Dispositivo')
                            ->placeholder('-'),

                        TextEntry::make('offline_created_at')
                            ->label('Creado Offline')
                            ->dateTime('d/m/Y H:i')
                            ->placeholder('-'),

                        TextEntry::make('created_at')
                            ->label('Fecha de Creación')
                            ->dateTime('d/m/Y H:i'),

                        TextEntry::make('updated_at')
                            ->label('Última Actualización')
                            ->dateTime('d/m/Y H:i'),
                    ])
                    ->columns(4),
            ]);
    }
}
