<?php

namespace App\Filament\Resources\SaleResource\RelationManagers;

use App\Enums\AccountFeeType;
use App\Enums\Currency;
use App\Models\Account;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

class PaymentsRelationManager extends RelationManager
{
    protected static string $relationship = 'payments';
    protected static ?string $title = 'Pagos registrados';

    public function form(Form $form): Form
    {
        return $form->schema([
            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()
                ->live()
                ->helperText(fn (Get $get) => Account::find($get('account_id'))?->fee_type === AccountFeeType::Takenos
                    ? '⚠ Takenos: se calculará fee = (monto × 5%) + $0.50. Solo acepta USD.'
                    : null),

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

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

            Forms\Components\Select::make('currency')
                ->label('Moneda del pago')
                ->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 (calculada automáticamente)')
                ->numeric()
                ->prefix('$')
                ->disabled()
                ->dehydrated()
                ->default(0),

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

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

    public 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('account.name')
                    ->label('Cuenta'),

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

                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'),

                Tables\Columns\TextColumn::make('note')
                    ->label('Nota')
                    ->limit(40),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label('Registrar pago')
                    ->mutateFormDataUsing(function (array $data): array {
                        $data['created_by_user_id'] = auth()->id();
                        return $data;
                    }),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ]);
    }

    public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
    {
        return true;
    }
}
