<?php

namespace App\Filament\Resources;

use App\Enums\Currency;
use App\Filament\Resources\PaymentResource\Pages;
use App\Models\Account;
use App\Models\Payment;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class PaymentResource extends Resource
{
    protected static ?string $model = Payment::class;
    protected static ?string $navigationIcon   = 'heroicon-o-credit-card';
    protected static ?string $navigationGroup  = 'Finanzas';
    protected static ?string $navigationLabel  = 'Pagos';
    protected static ?string $modelLabel       = 'Pago';
    protected static ?string $pluralModelLabel = 'Pagos';
    protected static ?int    $navigationSort   = 1;

    // ── Permisos ──────────────────────────────────────────────────────────────
    // Gestor puede CREAR pagos (los recibe del cliente) pero no editar/borrar
    public static function canViewAny(): bool { return true; }
    public static function canCreate(): bool  { return true; }
    public static function canEdit($record): bool
    {
        return auth()->user()?->isAdmin() || auth()->user()?->isContador();
    }
    public static function canDelete($record): bool
    {
        return auth()->user()?->isAdmin() || auth()->user()?->isContador();
    }

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make()->schema([
                Forms\Components\Select::make('sale_id')
                    ->label('Venta')
                    ->relationship('sale', 'title')
                    ->searchable()
                    ->preload()
                    ->required(),

                Forms\Components\Select::make('account_id')
                    ->label('Cuenta destino')
                    ->options(Account::orderBy('name')->get()->mapWithKeys(
                        fn ($a) => [$a->id => "{$a->name} ({$a->currency->value})"]
                    ))
                    ->required(),

                Forms\Components\DatePicker::make('payment_date')
                    ->label('Fecha de pago')
                    ->required()
                    ->default(now()),

                Forms\Components\TextInput::make('amount')
                    ->label('Monto')
                    ->numeric()
                    ->prefix('$')
                    ->step(0.01)
                    ->required()
                    ->minValue(0.01),

                Forms\Components\Select::make('currency')
                    ->label('Moneda')
                    ->options(collect(Currency::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()]))
                    ->required()
                    ->default(Currency::USD->value),

                Forms\Components\TextInput::make('fee_amount')
                    ->label('Comisión')
                    ->numeric()->prefix('$')->disabled()->dehydrated()->default(0),

                Forms\Components\TextInput::make('net_amount')
                    ->label('Neto')
                    ->numeric()->prefix('$')->disabled()->dehydrated()->default(0),

                Forms\Components\Textarea::make('note')
                    ->label('Nota')
                    ->rows(2)
                    ->columnSpanFull(),
            ])->columns(2),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('payment_date')
                    ->label('Fecha')
                    ->date('d/m/Y')
                    ->sortable(),

                Tables\Columns\TextColumn::make('sale.client.name')
                    ->label('Cliente')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\BadgeColumn::make('sale.client.origin')
                    ->label('Origen')
                    ->formatStateUsing(fn ($state) => match($state instanceof \App\Enums\ClientOrigin ? $state->value : $state) {
                        'upwork'               => 'Upwork',
                        'manual_internacional' => 'Internacional',
                        'bolivia'              => 'Bolivia',
                        'renovacion'           => 'Renovación',
                        default                => $state,
                    })
                    ->colors([
                        'success' => fn ($state) => ($state instanceof \App\Enums\ClientOrigin ? $state->value : $state) === 'upwork',
                        'info'    => fn ($state) => ($state instanceof \App\Enums\ClientOrigin ? $state->value : $state) === 'manual_internacional',
                        'warning' => fn ($state) => ($state instanceof \App\Enums\ClientOrigin ? $state->value : $state) === 'bolivia',
                        'gray'    => fn ($state) => ($state instanceof \App\Enums\ClientOrigin ? $state->value : $state) === 'renovacion',
                    ]),

                Tables\Columns\TextColumn::make('sale.title')
                    ->label('Venta')
                    ->searchable()
                    ->limit(35),

                Tables\Columns\TextColumn::make('account.name')
                    ->label('Cuenta')
                    ->sortable(),

                Tables\Columns\BadgeColumn::make('currency')
                    ->label('Mon.')
                    ->formatStateUsing(fn ($state) => $state instanceof Currency ? $state->value : $state)
                    ->colors(['success' => 'USD', 'warning' => 'BOB']),

                Tables\Columns\TextColumn::make('amount')
                    ->label('Monto')
                    ->numeric(decimalPlaces: 2)
                    ->prefix('$')
                    ->sortable(),

                Tables\Columns\TextColumn::make('fee_amount')
                    ->label('Comisión')
                    ->numeric(decimalPlaces: 2)
                    ->prefix('$'),

                Tables\Columns\TextColumn::make('net_amount')
                    ->label('Neto')
                    ->numeric(decimalPlaces: 2)
                    ->prefix('$')
                    ->color('success')
                    ->sortable(),

                Tables\Columns\TextColumn::make('note')
                    ->label('Nota')
                    ->limit(30)
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('account_id')
                    ->label('Cuenta')
                    ->relationship('account', 'name'),

                Tables\Filters\SelectFilter::make('currency')
                    ->label('Moneda')
                    ->options(collect(Currency::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()])),

                Tables\Filters\Filter::make('payment_date')
                    ->form([
                        Forms\Components\DatePicker::make('from')->label('Desde'),
                        Forms\Components\DatePicker::make('until')->label('Hasta'),
                    ])
                    ->query(function ($query, array $data) {
                        return $query
                            ->when($data['from'], fn ($q) => $q->whereDate('payment_date', '>=', $data['from']))
                            ->when($data['until'], fn ($q) => $q->whereDate('payment_date', '<=', $data['until']));
                    }),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->defaultSort('payment_date', 'desc');
    }

    public static function getRelations(): array
    {
        return [];
    }

    public static function getPages(): array
    {
        return [
            'index'  => Pages\ListPayments::route('/'),
            'create' => Pages\CreatePayment::route('/create'),
            'edit'   => Pages\EditPayment::route('/{record}/edit'),
        ];
    }
}
