<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ChestOpeningResource\Pages;
use App\Models\ChestOpening;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class ChestOpeningResource extends Resource
{
    protected static ?string $model = ChestOpening::class;

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

    protected static ?string $navigationLabel = 'Premios Ganados';

    protected static ?string $modelLabel = 'Premio Ganado';

    protected static ?string $pluralModelLabel = 'Premios Ganados';

    public static function canCreate(): bool
    {
        return false;
    }

    public static function canEdit($record): bool
    {
        return false;
    }

    public static function canDelete($record): bool
    {
        return false;
    }

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

                        Forms\Components\Select::make('raffle_id')
                            ->label('Sorteo')
                            ->relationship('raffle', 'title')
                            ->required(),

                        Forms\Components\Select::make('chest_prize_id')
                            ->label('Premio Ganado')
                            ->relationship('chestPrize', 'name')
                            ->required(),
                            
                        Forms\Components\Placeholder::make('prize_type')
                            ->label('Tipo de Premio')
                            ->content(fn (ChestOpening $record): string => match ($record->chestPrize?->type) {
                                'action' => 'Acción (Sorteo Mayor)',
                                'extra_key' => 'Llave Extra',
                                'wallet_credit' => 'Crédito de Billetera (₡' . number_format($record->chestPrize?->value ?? 0, 2) . ')',
                                'physical_prize' => 'Premio Físico',
                                default => 'Desconocido',
                            }),

                        Forms\Components\Placeholder::make('created_at')
                            ->label('Fecha de Apertura')
                            ->content(fn (ChestOpening $record): string => $record->created_at?->format('d/m/Y H:i:s') ?? '-'),
                    ])
                    ->columns(2),
            ]);
    }

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

                Tables\Columns\TextColumn::make('raffle.title')
                    ->label('Sorteo')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('chestPrize.name')
                    ->label('Premio Ganado')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('chestPrize.type')
                    ->label('Tipo de Premio')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'action' => 'info',
                        'extra_key' => 'warning',
                        'wallet_credit' => 'success',
                        'physical_prize' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'action' => 'Acción Sorteo',
                        'extra_key' => 'Llave Extra',
                        'wallet_credit' => 'Crédito Wallet',
                        'physical_prize' => 'Premio Físico',
                        default => $state,
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('chestPrize.value')
                    ->label('Valor Recompensa')
                    ->numeric(decimalPlaces: 2)
                    ->prefix('₡')
                    ->sortable()
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Fecha de Apertura')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('raffle')
                    ->relationship('raffle', 'title')
                    ->label('Sorteo'),

                Tables\Filters\SelectFilter::make('prize_type')
                    ->label('Tipo de Premio')
                    ->options([
                        'action' => 'Acción (Sorteo Mayor)',
                        'extra_key' => 'Llave Extra',
                        'wallet_credit' => 'Crédito de Billetera',
                        'physical_prize' => 'Premio Físico',
                    ])
                    ->query(function (Builder $query, array $data) {
                        if (empty($data['value'])) {
                            return $query;
                        }
                        return $query->whereHas('chestPrize', function (Builder $q) use ($data) {
                            $q->where('type', $data['value']);
                        });
                    }),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([
                // No bulk actions for database audit logs
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListChestOpenings::route('/'),
        ];
    }
}
