<?php

namespace App\Filament\Resources\Credits\Support;

use App\Models\Credit;
use App\Support\Format;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Utilities\Get as GetSchema;
use Filament\Support\Enums\FontWeight;

class CreditContextTabsBuilder
{
    /**
     * Cache local por request/render (evita múltiples Credit::find() por cada entry).
     * No persiste entre requests.
     *
     * @var array<int, Credit|null>
     */
    protected static array $creditCache = [];

    protected static function credit(GetSchema $get): ?Credit
    {
        $creditId = (int) ($get('credit_id') ?? request()->integer('credit_id'));
        if ($creditId <= 0) {
            return null;
        }

        if (! array_key_exists($creditId, self::$creditCache)) {
            self::$creditCache[$creditId] = Credit::with([
                'client',
                'payments.registeredBy',
                'installments',
                'auditLogs.user',
            ])->find($creditId);
        }

        return self::$creditCache[$creditId];
    }

    protected static function collectionDayLabel(?Credit $credit): string
    {
        if (! $credit) {
            return '—';
        }

        return match ($credit->periodicity) {
            'weekly' => match ((int) $credit->due_day_1) {
                1 => 'Lunes',
                2 => 'Martes',
                3 => 'Miércoles',
                4 => 'Jueves',
                5 => 'Viernes',
                6 => 'Sábado',
                7 => 'Domingo',
                default => '—',
            },

            'biweekly' => $credit->due_day_1 && $credit->due_day_2
                ? "Quincenal ({$credit->due_day_1} y {$credit->due_day_2})"
                : 'Quincenal',

            'monthly' => $credit->due_day_1
                ? "Mensual ({$credit->due_day_1})"
                : 'Mensual',

            'daily' => 'Diario',

            default => '—',
        };
    }

    protected static function periodicityLabel(?string $state): string
    {
        return match ($state) {
            'daily' => 'Diaria',
            'weekly' => 'Semanal',
            'biweekly' => 'Quincenal',
            'monthly' => 'Mensual',
            default => $state ?? '—',
        };
    }

    /**
     * TABS: Crédito / Cuotas / Pagos / Auditoría (idéntico al CreditInfolist)
     * pero adaptado a contexto Form (sin $record automático).
     */
    public static function make(): Section
    {
        return Section::make('Contexto del crédito')
            ->description('Información completa del crédito, cuotas, pagos y auditoría.')
            ->collapsible()
            ->collapsed() // 👈 plegado inicialmente
            ->columnSpan('full')
            ->schema([
                Tabs::make('creditTabs')
                    ->columnSpan('full')
                    ->tabs([
                        /*=========================================
                    | TAB 1: CRÉDITO
                    =========================================*/
                        Tab::make('Crédito')
                            ->icon('heroicon-m-information-circle')
                            ->schema([
                                Section::make('Información del crédito')
                                    ->columns(4)
                                    ->schema([
                                        TextEntry::make('client.name')
                                            ->label('Cliente')
                                            ->icon('heroicon-m-user')
                                            ->state(fn (GetSchema $get) => self::credit($get)?->client?->name ?? '—'),

                                        TextEntry::make('status')
                                            ->label('Estado')
                                            ->badge()
                                            ->state(fn (GetSchema $get) => self::credit($get)?->getStatusLabel() ?? '—'
                                            )
                                            ->color(fn (GetSchema $get) => self::credit($get)?->getStatusBadgeColor() ?? 'gray'
                                            ),

                                        TextEntry::make('periodicity')
                                            ->label('Periodicidad')
                                            ->badge()
                                            ->state(fn (GetSchema $get) => self::credit($get)?->periodicity)
                                            ->formatStateUsing(fn ($state) => self::periodicityLabel($state)),

                                        TextEntry::make('collection_day')
                                            ->label('Día de Cobro')
                                            ->state(fn (GetSchema $get) => self::collectionDayLabel(self::credit($get)))
                                            ->badge()
                                            ->color('info'),

                                        TextEntry::make('start_date')
                                            ->label('Inicio')
                                            ->date()
                                            ->state(fn (GetSchema $get) => self::credit($get)?->start_date),

                                        TextEntry::make('due_date')
                                            ->label('Vencimiento Final')
                                            ->date()
                                            ->state(fn (GetSchema $get) => self::credit($get)?->due_date),

                                        TextEntry::make('installments_count')
                                            ->label('Total Cuotas')
                                            ->icon('heroicon-m-list-bullet')
                                            ->state(fn (GetSchema $get) => self::credit($get)?->installments_count ?? '—'),

                                        TextEntry::make('installments_progress')
                                            ->label('Cuotas (Pagadas / Pendientes)')
                                            ->state(function (GetSchema $get): string {
                                                $c = self::credit($get);
                                                if (! $c) {
                                                    return '—';
                                                }

                                                return sprintf('%d / %d', (int) $c->installments_paid_count, (int) $c->installments_pending_count);
                                            })
                                            ->badge()
                                            ->color(fn (GetSchema $get) => (self::credit($get)?->installments_pending_count ?? 1) === 0
                                                    ? 'success'
                                                    : 'warning'
                                            ),

                                        TextEntry::make('amount')
                                            ->label('Capital Prestado')
                                            ->state(fn (GetSchema $get) => self::credit($get)?->amount)
                                            ->formatStateUsing(fn ($state) => Format::money($state))
                                            ->color('gray'),

                                        TextEntry::make('total_receivable')
                                            ->label('Total a Pagar')
                                            ->state(fn (GetSchema $get) => self::credit($get)?->total_receivable)
                                            ->formatStateUsing(fn ($state) => Format::money($state))
                                            ->weight(FontWeight::Bold),

                                        TextEntry::make('total_paid')
                                            ->label('Total Recaudado')
                                            ->state(fn (GetSchema $get) => self::credit($get)?->total_paid)
                                            ->formatStateUsing(fn ($state) => Format::money($state))
                                            ->color('success'),

                                        TextEntry::make('remaining_balance')
                                            ->label('Total Pendiente')
                                            ->state(fn (GetSchema $get) => self::credit($get)?->remaining_balance)
                                            ->formatStateUsing(fn ($state) => Format::money($state))
                                            ->weight(FontWeight::Bold)
                                            ->color(fn ($state) => ((float) $state) > 0 ? 'danger' : 'success'),
                                    ]),
                            ]),

                        /*=========================================
                    | TAB 2: CUOTAS
                    =========================================*/
                        Tab::make('Cuotas')
                            ->icon('heroicon-m-calendar-days')
                            ->badge(function (GetSchema $get) {
                                $c = self::credit($get);
                                if (! $c) {
                                    return null;
                                }

                                return $c->installments->where('status', 'overdue')->count() > 0 ? '!' : null;
                            })
                            ->badgeColor('danger')
                            ->schema([
                                RepeatableEntry::make('installments')
                                    ->label('Cronograma de Cuotas')
                                    ->contained(true)
                                    ->columns(6)
                                    ->state(fn (GetSchema $get) => self::credit($get)?->installments?->values()->all() ?? [])
                                    ->schema([
                                        TextEntry::make('installment_number')->label('Cuota')->prefix('#'),
                                        TextEntry::make('due_date')->label('Vencimiento')->date(),
                                        TextEntry::make('total_amount')->label('Valor Cuota')->formatStateUsing(fn ($state) => Format::money($state)),
                                        TextEntry::make('amount_paid')->label('Monto Pagado')->formatStateUsing(fn ($state) => Format::money($state)),

                                        TextEntry::make('status')
                                            ->label('Estado')
                                            ->badge()
                                            ->color(fn ($record) => method_exists($record, 'getStatusBadgeColor') ? $record->getStatusBadgeColor() : 'gray')
                                            ->formatStateUsing(fn ($record) => method_exists($record, 'getStatusLabel') ? $record->getStatusLabel() : ($record->status ?? '—')),

                                        TextEntry::make('paid_date')->label('Pagado el')->date()->placeholder('-'),
                                    ]),
                            ]),

                        /*=========================================
                    | TAB 3: PAGOS
                    =========================================*/
                        Tab::make('Pagos')
                            ->icon('heroicon-m-banknotes')
                            ->schema([
                                RepeatableEntry::make('payments')
                                    ->label('Pagos Registrados')
                                    ->contained(true)
                                    ->columns(5)
                                    ->state(fn (GetSchema $get) => self::credit($get)?->payments?->sortByDesc('payment_date')->values()->all() ?? [])
                                    ->schema([
                                        TextEntry::make('payment_date')->label('Fecha')->date(),

                                        TextEntry::make('amount')
                                            ->label('Monto Recibido')
                                            ->formatStateUsing(fn ($state) => Format::money($state))
                                            ->weight(FontWeight::Bold)
                                            ->color('success'),

                                        TextEntry::make('payment_method')
                                            ->label('Medio')
                                            ->badge()
                                            ->formatStateUsing(fn (?string $state): string => match ($state) {
                                                'cash' => 'Efectivo',
                                                'transfer' => 'Transferencia',
                                                'nequi' => 'Nequi',
                                                'daviplata' => 'Daviplata',
                                                'bancolombia' => 'Bancolombia',
                                                null => '-',
                                                default => ucfirst($state),
                                            }),

                                        TextEntry::make('id')->label('Ref. Pago')->prefix('#PAY-'),

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

                        /*=========================================
                    | TAB 4: AUDITORÍA
                    =========================================*/
                        Tab::make('Auditoría')
                            ->icon('heroicon-m-clipboard-document-list')
                            ->schema([
                                Section::make('Eventos de crédito')
                                    ->schema([
                                        RepeatableEntry::make('auditLogs')
                                            ->label('Historial de operaciones')
                                            ->columns(3)
                                            ->contained(true)
                                            ->state(fn (GetSchema $get) => self::credit($get)?->auditLogs?->sortByDesc('created_at')->values()->all() ?? [])
                                            ->schema([
                                                TextEntry::make('created_at')->label('Fecha')->dateTime('d/m/Y H:i'),
                                                TextEntry::make('action')->label('Acción')->badge(),
                                                TextEntry::make('user.name')->label('Usuario')->icon('heroicon-m-user'),
                                            ]),
                                    ]),
                            ]),
                    ]),
            ]);
    }
}
