<?php

namespace App\Filament\Resources\Expenses\Schemas;

use App\Models\Company;
use App\Models\Credit;
use App\Models\User;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get as GetSchema;
use Filament\Schemas\Schema;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class ExpenseForm
{
    public static function configure(Schema $schema): Schema
    {
        $user = Auth::user();
        $isSuperAdmin = $user->hasRole('super_admin');
        $currentCompany = $isSuperAdmin ? null : $user->company_id;

        return $schema
            ->components([
                Section::make('Datos del egreso')
                    ->description('Registra un egreso asociado opcionalmente a un crédito.')
                    ->columns(2)
                    ->columnSpanFull()
                    ->schema([
                        /** AFECTA EFECTIVO */
                        Hidden::make('affects_cash'),

                        /** COMPANY ID (multi-tenant) */
                        ! $isSuperAdmin
                            ? Hidden::make('company_id')
                                ->default($currentCompany)
                            : null,

                        Select::make('company_id')
                            ->label('Compañía')
                            ->relationship('company', 'name')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->hidden(! $isSuperAdmin)
                            ->default($currentCompany)
                            ->live(), // reactivo para refrescar créditos y responsables

                        /** FECHA DE OPERACIÓN */
                        DatePicker::make('operation_date')
                            ->label('Fecha de operación')
                            ->default(now())
                            ->required(),

                        /** MONTO */
                        TextInput::make('amount')
                            ->label('Monto')
                            ->numeric()
                            ->inputMode('decimal')
                            ->minValue(0.01)
                            ->required(),

                        /** TIPO DE EGRESO */
                        Select::make('expense_type')
                            ->label('Tipo de egreso')
                            ->options([
                                'credit_disbursement' => 'Desembolso de crédito',
                                'operational' => 'Gasto operativo',
                                'commission' => 'Comisión',
                                'profit_withdrawal' => 'Retiro de utilidades',
                                'bad_debt' => 'Castigo / incobrable',
                                'adjustment' => 'Ajuste contable',
                            ])
                            ->required()
                            ->reactive(),

                        /** MÉTODO DE PAGO */
                        Select::make('method')
                            ->label('Método de pago')
                            ->options([
                                'cash' => 'Efectivo',
                                'bank_transfer' => 'Transferencia bancaria',
                                'card' => 'Tarjeta',
                                'mobile_money' => 'Billetera digital',
                                'other' => 'Otro',
                            ])
                            ->searchable()
                            ->preload()
                            ->nullable(),

                        /** CRÉDITO ASOCIADO (OPCIONAL) */
                        Select::make('credit_id')
                            ->label('Crédito asociado')
                            ->relationship(
                                name: 'credit',
                                titleAttribute: 'id',
                                modifyQueryUsing: function (Builder $query, GetSchema $get) use ($currentCompany) {
                                    $company = $get('company_id') ?? $currentCompany;

                                    if ($company) {
                                        $query->where('company_id', $company);
                                    }

                                    return $query;
                                }
                            )
                            ->getOptionLabelFromRecordUsing(
                                fn (Credit $record) => "Crédito #{$record->code} - {$record->client?->name}"
                            )
                            ->searchable()
                            ->preload()
                            ->visible(fn (GetSchema $get) => in_array($get('expense_type'), ['credit_disbursement', 'bad_debt']))
                            ->required(fn (GetSchema $get) => $get('expense_type') === 'credit_disbursement')
                            ->nullable(),

                        /** RESPONSABLE / COBRADOR (OPCIONAL) */
                        Select::make('collector_user_id')
                            ->label('Responsable')
                            ->options(function (GetSchema $get) use ($currentCompany) {
                                $company = $get('company_id') ?? $currentCompany;
                                if (! $company) {
                                    return [];
                                }

                                return User::query()
                                    ->where('company_id', $company)
                                    ->role(['collector', 'supervisor'])
                                    ->pluck('name', 'id');
                            })
                            ->searchable()
                            ->preload()
                            ->nullable(),

                        /** REFERENCIA */
                        TextInput::make('reference')
                            ->label('Referencia')
                            ->maxLength(255)
                            ->nullable(),

                        /** NOTAS / DESCRIPCIÓN */
                        Textarea::make('notes')
                            ->label('Descripción / Observación')
                            ->rows(3)
                            ->nullable()
                            ->columnSpanFull(),

                        /** METADATA (JSON LIBRE) */
                        KeyValue::make('metadata')
                            ->label('Metadatos adicionales')
                            ->keyLabel('Clave')
                            ->valueLabel('Valor')
                            ->nullable()
                            ->columnSpanFull(),
                    ]),
            ]);
    }
}
