<?php

declare(strict_types=1);

namespace App\Filament\Resources\Partners\Schemas;

use App\Enums\OwnershipModel;
use App\Enums\PartnerStatus;
use App\Services\PartnerInvestmentService;
use Carbon\Carbon;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Enums\TextSize;

class PartnerInfolist
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([

                // ══════════════════════════════════════════════════════════════
                // RESUMEN FINANCIERO — KPIs patrimoniales del socio
                // ══════════════════════════════════════════════════════════════

                Section::make('Resumen financiero')
                    ->icon('heroicon-o-banknotes')
                    ->description('Estado patrimonial y de rentabilidad del socio a la fecha actual')
                    ->schema([

                        TextEntry::make('total_contributed')
                            ->label('Total aportado')
                            ->icon('heroicon-o-arrow-down-circle')
                            ->getStateUsing(fn ($record) => $record->getTotalContributed()->formatWithCurrency())
                            ->size(TextSize::Large)
                            ->weight('bold')
                            ->color('success'),

                        TextEntry::make('net_capital')
                            ->label('Capital neto (equity)')
                            ->icon('heroicon-o-building-library')
                            ->getStateUsing(fn ($record) => $record->getNetCapital()->formatWithCurrency())
                            ->size(TextSize::Large)
                            ->weight('bold')
                            ->color('primary'),

                        TextEntry::make('current_balance')
                            ->label('Balance actual')
                            ->icon('heroicon-o-wallet')
                            ->getStateUsing(fn ($record) => $record->getCurrentBalance()->formatWithCurrency())
                            ->size(TextSize::Large)
                            ->weight('bold')
                            ->color('warning'),

                        TextEntry::make('total_profits_received')
                            ->label('Utilidades recibidas')
                            ->icon('heroicon-o-chart-bar')
                            ->getStateUsing(fn ($record) => $record->getTotalProfitsReceived()->formatWithCurrency())
                            ->color('info'),

                        TextEntry::make('ownership_pct')
                            ->label('Participacion actual')
                            ->icon('heroicon-o-chart-pie')
                            ->getStateUsing(function ($record) {
                                $service = app(PartnerInvestmentService::class);
                                $percentages = $service->calculateOwnershipPercentages($record->company_id);

                                return isset($percentages[$record->id])
                                    ? $percentages[$record->id].'%'
                                    : '0.0000%';
                            })
                            ->color('purple'),

                        TextEntry::make('roi')
                            ->label('ROI (retorno sobre inversion)')
                            ->icon('heroicon-o-arrow-trending-up')
                            ->getStateUsing(fn ($record) => $record->getReturnOnInvestment().'%')
                            ->color(fn ($state, $record) => bccomp(
                                $record->getReturnOnInvestment(), '0', 2
                            ) > 0 ? 'success' : 'gray'),

                    ])
                    ->columns(3),

                // ══════════════════════════════════════════════════════════════
                // ACTIVIDAD — Contadores y fechas de movimientos
                // ══════════════════════════════════════════════════════════════

                Section::make('Actividad del socio')
                    ->icon('heroicon-o-arrow-path')
                    ->description('Resumen de movimientos registrados en el sistema')
                    ->schema([

                        TextEntry::make('contributions_count')
                            ->label('Aportes de capital')
                            ->icon('heroicon-o-arrow-down-circle')
                            ->getStateUsing(fn ($record) => (string) $record->contributions()->count())
                            ->suffix(' aporte(s)')
                            ->color('success'),

                        TextEntry::make('withdrawals_approved_count')
                            ->label('Retiros aprobados')
                            ->icon('heroicon-o-arrow-up-circle')
                            ->getStateUsing(fn ($record) => (string) $record->withdrawals()
                                ->where('approval_status', 'approved')
                                ->count()
                            )
                            ->suffix(' retiro(s)')
                            ->color('danger'),

                        TextEntry::make('withdrawals_pending_count')
                            ->label('Retiros pendientes')
                            ->icon('heroicon-o-clock')
                            ->getStateUsing(fn ($record) => (string) $record->withdrawals()
                                ->where('approval_status', 'pending')
                                ->count()
                            )
                            ->suffix(' retiro(s)')
                            ->color(fn ($state) => (int) $state > 0 ? 'warning' : 'gray'),

                        TextEntry::make('last_contribution_date')
                            ->label('Ultimo aporte')
                            ->icon('heroicon-o-calendar')
                            ->getStateUsing(function ($record) {
                                $date = $record->contributions()
                                    ->orderByDesc('operation_date')
                                    ->value('operation_date');

                                return $date
                                    ? Carbon::parse($date)->format('d M Y')
                                    : 'Sin aportes';
                            }),

                    ])
                    ->columns(4)
                    ->collapsible(),

                // ══════════════════════════════════════════════════════════════
                // DATOS DEL SOCIO — Información de identidad
                // ══════════════════════════════════════════════════════════════

                Section::make('Datos del socio')
                    ->icon('heroicon-o-user')
                    ->schema([

                        TextEntry::make('name')
                            ->label('Nombre completo')
                            ->icon('heroicon-o-user'),

                        TextEntry::make('document_display')
                            ->label('Documento de identidad')
                            ->icon('heroicon-o-identification')
                            ->getStateUsing(fn ($record) => $record->document_type
                                ? strtoupper($record->document_type).' '.$record->document_number
                                : '—'
                            ),

                        TextEntry::make('email')
                            ->label('Correo electronico')
                            ->icon('heroicon-o-envelope')
                            ->default('—')
                            ->copyable(),

                        TextEntry::make('phone')
                            ->label('Telefono')
                            ->icon('heroicon-o-phone')
                            ->default('—'),

                        TextEntry::make('status')
                            ->label('Estado')
                            ->badge()
                            ->formatStateUsing(fn ($state) => self::enumLabel($state, PartnerStatus::class))
                            ->color(fn ($state) => self::enumColor($state, PartnerStatus::class)),

                        TextEntry::make('joined_at')
                            ->label('Fecha de ingreso')
                            ->icon('heroicon-o-calendar')
                            ->date('d M Y'),

                        TextEntry::make('exited_at')
                            ->label('Fecha de salida')
                            ->icon('heroicon-o-calendar-days')
                            ->date('d M Y')
                            ->visible(fn ($record) => (bool) $record->exited_at),

                    ])
                    ->columns(3)
                    ->collapsible(),

                // ══════════════════════════════════════════════════════════════
                // MODELO DE PARTICIPACION — Configuración de ownership
                // ══════════════════════════════════════════════════════════════

                Section::make('Modelo de participacion')
                    ->icon('heroicon-o-chart-pie')
                    ->description('Define como se calcula el porcentaje de propiedad de este socio')
                    ->schema([

                        TextEntry::make('ownership_model')
                            ->label('Tipo de modelo')
                            ->badge()
                            ->formatStateUsing(fn ($state) => self::enumLabel($state, OwnershipModel::class))
                            ->color(fn ($state) => self::enumColor($state, OwnershipModel::class)),

                        TextEntry::make('fixed_ownership_percentage')
                            ->label('Porcentaje fijo asignado')
                            ->suffix('%')
                            ->visible(fn ($record) => self::resolveOwnershipModel($record) === OwnershipModel::FIXED),

                        TextEntry::make('ownership_description')
                            ->label('Como funciona este modelo')
                            ->icon('heroicon-o-information-circle')
                            ->getStateUsing(fn ($record) => self::resolveOwnershipModel($record)?->getDescription() ?? '—')
                            ->columnSpanFull(),

                    ])
                    ->columns(2)
                    ->collapsible(),

                // ══════════════════════════════════════════════════════════════
                // NOTAS
                // ══════════════════════════════════════════════════════════════

                Section::make('Notas')
                    ->icon('heroicon-o-chat-bubble-left-ellipsis')
                    ->schema([
                        TextEntry::make('notes')
                            ->label('')
                            ->columnSpanFull(),
                    ])
                    ->visible(fn ($record) => filled($record->notes))
                    ->collapsible(),

                // ══════════════════════════════════════════════════════════════
                // AUDITORIA
                // ══════════════════════════════════════════════════════════════

                Section::make('Registro del sistema')
                    ->icon('heroicon-o-clock')
                    ->schema([

                        TextEntry::make('id')
                            ->label('ID')
                            ->prefix('#')
                            ->copyable()
                            ->copyMessage('ID copiado'),

                        TextEntry::make('company.name')
                            ->label('Compania')
                            ->icon('heroicon-o-building-office'),

                        TextEntry::make('created_at')
                            ->label('Creado')
                            ->dateTime('d M Y, H:i'),

                        TextEntry::make('updated_at')
                            ->label('Ultima actualizacion')
                            ->dateTime('d M Y, H:i')
                            ->visible(fn ($record) => $record->updated_at?->ne($record->created_at)),

                    ])
                    ->columns(3)
                    ->collapsible()
                    ->collapsed(),

            ]);
    }

    // ══════════════════════════════════════════════════════════════════════════
    // HELPERS
    // ══════════════════════════════════════════════════════════════════════════

    private static function resolveOwnershipModel($record): ?OwnershipModel
    {
        $model = $record->ownership_model;

        if ($model instanceof OwnershipModel) {
            return $model;
        }

        return is_string($model) ? OwnershipModel::tryFrom($model) : null;
    }

    private static function enumLabel(mixed $state, string $enumClass): string
    {
        if ($state instanceof $enumClass) {
            return $state->getLabel();
        }

        if (is_string($state)) {
            return $enumClass::tryFrom($state)?->getLabel() ?? $state;
        }

        return '—';
    }

    private static function enumColor(mixed $state, string $enumClass, string $fallback = 'gray'): string
    {
        if ($state instanceof $enumClass) {
            return $state->getColor();
        }

        if (is_string($state)) {
            return $enumClass::tryFrom($state)?->getColor() ?? $fallback;
        }

        return $fallback;
    }
}
