<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TransactionResource\Pages;
use App\Models\Transaction;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class TransactionResource extends Resource
{
    protected static ?string $model = Transaction::class;

    protected static ?string $navigationIcon = 'heroicon-o-banknotes';

    protected static ?string $navigationLabel = 'Transacciones';

    protected static ?string $modelLabel = 'Transacción';

    protected static ?string $pluralModelLabel = 'Transacciones';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Detalle del Movimiento')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->label('Usuario / Cliente')
                            ->relationship('user', 'name')
                            ->searchable()
                            ->required(),

                        Forms\Components\TextInput::make('amount')
                            ->label('Monto')
                            ->numeric()
                            ->prefix('₡')
                            ->required(),

                        Forms\Components\Select::make('type')
                            ->label('Tipo de Movimiento')
                            ->options([
                                'deposit' => 'Depósito (Cargar Wallet)',
                                'withdrawal' => 'Retiro (Retirar Fondos)',
                                'purchase' => 'Compra de Boletos',
                                'commission_payout' => 'Pago de Comisión',
                                'points_redeem' => 'Canje de Puntos',
                            ])
                            ->required(),

                        Forms\Components\Select::make('payment_method')
                            ->label('Método de Pago')
                            ->options([
                                'card' => 'Tarjeta Crédito/Débito',
                                'sinpe' => 'SINPE Móvil',
                                'transfer' => 'Transferencia Bancaria',
                                'wallet' => 'Billetera Interna (Wallet)',
                            ])
                            ->required(),

                        Forms\Components\TextInput::make('payment_reference')
                            ->label('Referencia / Código Comprobante')
                            ->maxLength(255),

                        Forms\Components\FileUpload::make('payment_screenshot')
                            ->label('Captura del Comprobante (SINPE)')
                            ->disk('public')
                            ->directory('payments')
                            ->image()
                            ->columnSpanFull()
                            ->visible(fn ($get) => $get('payment_method') === 'sinpe'),

                        Forms\Components\Select::make('status')
                            ->label('Estado de Transacción')
                            ->options([
                                'pending' => 'Pendiente de Aprobación',
                                'approved' => 'Aprobada / Completada',
                                'rejected' => 'Rechazada',
                            ])
                            ->required()
                            ->default('pending'),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Usuario')
                    ->searchable()
                    ->sortable(),

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

                Tables\Columns\TextColumn::make('type')
                    ->label('Tipo')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'deposit' => 'success',
                        'withdrawal' => 'warning',
                        'purchase' => 'info',
                        'commission_payout' => 'gray',
                        'points_redeem' => 'primary',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'deposit' => 'Depósito',
                        'withdrawal' => 'Retiro',
                        'purchase' => 'Compra',
                        'commission_payout' => 'Pago Comisión',
                        'points_redeem' => 'Canje Puntos',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('payment_method')
                    ->label('Método')
                    ->badge()
                    ->color('gray')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'card' => 'Tarjeta',
                        'sinpe' => 'SINPE',
                        'transfer' => 'Transferencia',
                        'wallet' => 'Wallet',
                    }),

                Tables\Columns\TextColumn::make('payment_reference')
                    ->label('Referencia')
                    ->searchable(),

                Tables\Columns\ImageColumn::make('payment_screenshot')
                    ->label('Captura SINPE')
                    ->disk('public')
                    ->size(40)
                    ->square()
                    ->placeholder('Sin imagen'),

                Tables\Columns\TextColumn::make('status')
                    ->label('Estado')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'pending' => 'warning',
                        'approved' => 'success',
                        'rejected' => 'danger',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'pending' => 'Pendiente',
                        'approved' => 'Aprobado',
                        'rejected' => 'Rechazado',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Fecha')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->label('Tipo')
                    ->options([
                        'deposit' => 'Depósitos',
                        'withdrawal' => 'Retiros',
                        'purchase' => 'Compras',
                        'commission_payout' => 'Pagos de Comisión',
                        'points_redeem' => 'Canje de Puntos',
                    ]),
                Tables\Filters\SelectFilter::make('status')
                    ->label('Estado')
                    ->options([
                        'pending' => 'Pendientes',
                        'approved' => 'Aprobados',
                        'rejected' => 'Rechazados',
                    ]),
            ])
            ->actions([
                Tables\Actions\Action::make('approve')
                    ->label('Aprobar')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->modalHeading('¿Aprobar esta transacción?')
                    ->modalDescription('Si es una compra de tarjetas, se emitirán con su rareza, se acreditarán las llaves y el cliente recibirá una notificación push para revelarlas.')
                    ->visible(fn ($record) => $record->status === 'pending')
                    ->action(function ($record) {
                        $record->update([
                            'status' => 'approved',
                            'approved_at' => now(),
                        ]);

                        \Filament\Notifications\Notification::make()
                            ->title('Transacción aprobada')
                            ->body('El cliente fue notificado por push.')
                            ->success()
                            ->send();
                    }),
                Tables\Actions\Action::make('reject')
                    ->label('Rechazar')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->modalHeading('¿Rechazar esta transacción?')
                    ->visible(fn ($record) => $record->status === 'pending')
                    ->action(function ($record) {
                        $record->update([
                            'status' => 'rejected',
                            'rejected_at' => now(),
                        ]);

                        \Filament\Notifications\Notification::make()
                            ->title('Transacción rechazada')
                            ->danger()
                            ->send();
                    }),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

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