<?php

namespace App\Filament\Resources;

use App\Filament\Resources\RaffleResource\Pages;
use App\Models\Raffle;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class RaffleResource extends Resource
{
    protected static ?string $model = Raffle::class;

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

    protected static ?string $navigationLabel = 'Sorteos';

    protected static ?string $modelLabel = 'Sorteo';

    protected static ?string $pluralModelLabel = 'Sorteos';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Información Básica')
                            ->schema([
                                Forms\Components\TextInput::make('title')
                                    ->label('Título del Sorteo')
                                    ->required()
                                    ->maxLength(255),

                                Forms\Components\Grid::make(2)
                                    ->schema([
                                        Forms\Components\Select::make('type')
                                            ->label('Tipo de Sorteo')
                                            ->options([
                                                'main' => 'Principal',
                                                'secondary' => 'Secundario (Rápido)',
                                            ])
                                            ->default('main')
                                            ->required(),

                                        Forms\Components\Select::make('status')
                                            ->label('Estado')
                                            ->options([
                                                'draft' => 'Borrador',
                                                'active' => 'Activo',
                                                'completed' => 'Completado',
                                                'cancelled' => 'Cancelado',
                                            ])
                                            ->default('draft')
                                            ->required(),
                                    ]),

                                Forms\Components\DateTimePicker::make('draw_date')
                                    ->label('Fecha y Hora del Sorteo')
                                    ->required()
                                    ->native(false),

                                Forms\Components\Textarea::make('description')
                                    ->label('Descripción Detallada')
                                    ->required()
                                    ->rows(4),

                                Forms\Components\Textarea::make('rules')
                                    ->label('Reglamento Oficial')
                                    ->rows(3),
                            ]),

                        Forms\Components\Section::make('Precios y Emisión de Tarjetas')
                            ->description('Cada sorteo emite tarjetas con número único (0 al total - 1). Un número comprado no puede volver a comprarse.')
                            ->schema([
                                Forms\Components\Grid::make(4)
                                    ->schema([
                                        Forms\Components\TextInput::make('total_tickets')
                                            ->label('Total de Tarjetas')
                                            ->helperText('Ej: 10000 = números 0000 a 9999')
                                            ->numeric()
                                            ->required()
                                            ->default(10000)
                                            ->minValue(1),

                                        Forms\Components\TextInput::make('ticket_price')
                                            ->label('Precio por Tarjeta')
                                            ->numeric()
                                            ->prefix('₡')
                                            ->required()
                                            ->default(1500.00),

                                        Forms\Components\TextInput::make('commercial_value')
                                            ->label('Valor Comercial')
                                            ->numeric()
                                            ->prefix('₡')
                                            ->required(),

                                        Forms\Components\TextInput::make('fiscal_value')
                                            ->label('Valor Fiscal')
                                            ->numeric()
                                            ->prefix('₡')
                                            ->required(),
                                    ]),
                            ]),

                        Forms\Components\Section::make('Rarezas y Llaves')
                            ->description('Probabilidad de cada rareza al comprar una tarjeta y cuántas llaves otorga. Las probabilidades deben sumar 100%.')
                            ->schema([
                                Forms\Components\Repeater::make('rarity_config')
                                    ->label('Configuración de Rarezas')
                                    ->schema([
                                        Forms\Components\Select::make('rarity')
                                            ->label('Rareza')
                                            ->options([
                                                'common' => 'Común',
                                                'uncommon' => 'Poco Común',
                                                'rare' => 'Rara',
                                                'epic' => 'Épica',
                                                'legendary' => 'Legendaria',
                                                'mythic' => 'Mítica (legado, no recomendado en sorteos nuevos)',
                                            ])
                                            ->required(),
                                        Forms\Components\TextInput::make('probability')
                                            ->label('Probabilidad (%)')
                                            ->numeric()
                                            ->required()
                                            ->minValue(0)
                                            ->maxValue(100),
                                        Forms\Components\TextInput::make('keys')
                                            ->label('Llaves que otorga')
                                            ->numeric()
                                            ->required()
                                            ->minValue(0)
                                            ->default(0),
                                    ])
                                    ->columns(3)
                                    ->default(\App\Models\Raffle::DEFAULT_RARITY_CONFIG)
                                    ->reorderable(false)
                                    ->createItemButtonLabel('Agregar Rareza'),
                            ]),

                        Forms\Components\Section::make('Descuentos por Volumen')
                            ->description('Descuento aplicado al total según la cantidad de tarjetas compradas. Se aplica el tier más alto alcanzado.')
                            ->schema([
                                Forms\Components\Repeater::make('discount_tiers')
                                    ->label('Tiers de Descuento')
                                    ->schema([
                                        Forms\Components\TextInput::make('min_quantity')
                                            ->label('Desde (cantidad de tarjetas)')
                                            ->numeric()
                                            ->required()
                                            ->minValue(2)
                                            ->default(5),
                                        Forms\Components\TextInput::make('discount_percent')
                                            ->label('Descuento (%)')
                                            ->numeric()
                                            ->required()
                                            ->minValue(0)
                                            ->maxValue(100)
                                            ->default(5),
                                    ])
                                    ->columns(2)
                                    ->default([
                                        ['min_quantity' => 3, 'discount_percent' => 10],
                                        ['min_quantity' => 5, 'discount_percent' => 15],
                                        ['min_quantity' => 10, 'discount_percent' => 20],
                                    ])
                                    ->createItemButtonLabel('Agregar Tier de Descuento'),
                            ]),

                        Forms\Components\Section::make('Premios del Cofre')
                            ->description('Configura los premios y probabilidades de ganar para las llaves usadas en este sorteo.')
                            ->schema([
                                Forms\Components\Repeater::make('chestPrizes')
                                    ->relationship('chestPrizes')
                                    ->schema([
                                        Forms\Components\TextInput::make('name')
                                            ->label('Nombre del Premio')
                                            ->required(),
                                        Forms\Components\Select::make('type')
                                            ->label('Tipo')
                                            ->options([
                                                'extra_key' => 'Llave(s) Extra',
                                                'wallet_credit' => 'Saldo de Wallet',
                                                'physical_prize' => 'Premio Físico',
                                            ])
                                            ->required()
                                            ->reactive(),
                                        Forms\Components\TextInput::make('value')
                                            ->label('Monto de Crédito / Cantidad de Llaves')
                                            ->numeric()
                                            ->visible(fn (callable $get) => in_array($get('type'), ['wallet_credit', 'extra_key']))
                                            ->required(fn (callable $get) => in_array($get('type'), ['wallet_credit', 'extra_key']))
                                            ->default(0.00),
                                        Forms\Components\TextInput::make('probability')
                                            ->label('Probabilidad (%)')
                                            ->numeric()
                                            ->required()
                                            ->minValue(0.01)
                                            ->maxValue(100.00)
                                            ->default(10.00),
                                        Forms\Components\TextInput::make('total_quantity')
                                            ->label('Cantidad Total')
                                            ->numeric()
                                            ->required()
                                            ->minValue(1)
                                            ->default(10)
                                            ->reactive()
                                            ->afterStateUpdated(fn ($state, callable $set) => $set('remaining_quantity', $state)),
                                        Forms\Components\TextInput::make('remaining_quantity')
                                            ->label('Cantidad Restante')
                                            ->numeric()
                                            ->required()
                                            ->default(10),
                                        Forms\Components\FileUpload::make('image_path')
                                            ->label('Imagen del Premio')
                                            ->image()
                                            ->disk('public')
                                            ->directory('prizes')
                                            ->columnSpanFull(),
                                    ])
                                    ->columns(3)
                                    ->grid(2)
                                    ->createItemButtonLabel('Agregar Premio al Cofre'),
                            ]),
                    ])
                    ->columnSpan(['lg' => 2]),

                Forms\Components\Group::make()
                    ->schema([
                        Forms\Components\Section::make('Multimedia del Premio')
                            ->schema([
                                Forms\Components\FileUpload::make('images_json')
                                    ->label('Fotos Reales del Premio')
                                    ->multiple()
                                    ->image()
                                    ->disk('public')
                                    ->directory('raffles/gallery')
                                    ->reorderable()
                                    ->appendFiles(),

                                Forms\Components\TextInput::make('video_url')
                                    ->label('Enlace de Video (URL)')
                                    ->url()
                                    ->placeholder('https://youtube.com/...'),
                            ]),

                        Forms\Components\Section::make('Documentos de Transparencia')
                            ->schema([
                                Forms\Components\FileUpload::make('invoice_path')
                                    ->label('Factura de Compra (PDF/Imagen)')
                                    ->disk('public')
                                    ->directory('raffles/transparency')
                                    ->acceptedFileTypes(['application/pdf', 'image/*']),

                                Forms\Components\FileUpload::make('vehicle_docs_path')
                                    ->label('Título/Doc Vehículo')
                                    ->disk('public')
                                    ->directory('raffles/transparency')
                                    ->acceptedFileTypes(['application/pdf', 'image/*']),

                                Forms\Components\FileUpload::make('marchamo_path')
                                    ->label('Comprobante de Marchamo')
                                    ->disk('public')
                                    ->directory('raffles/transparency')
                                    ->acceptedFileTypes(['application/pdf', 'image/*']),

                                Forms\Components\FileUpload::make('inspection_path')
                                    ->label('Hoja RITEVE / DEKRA')
                                    ->disk('public')
                                    ->directory('raffles/transparency')
                                    ->acceptedFileTypes(['application/pdf', 'image/*']),
                            ]),

                        Forms\Components\Section::make('Ganador del Sorteo (Asignación Manual)')
                            ->description('Asigna o modifica manualmente el usuario y tarjeta ganadora del sorteo.')
                            ->schema([
                                Forms\Components\Select::make('winner_user_id')
                                    ->label('Usuario Ganador')
                                    ->relationship('winner', 'name')
                                    ->searchable()
                                    ->nullable(),

                                Forms\Components\Select::make('winner_action_ticket_id')
                                    ->label('Tarjeta / Acción Ganadora')
                                    ->options(function (callable $get, ?Raffle $record) {
                                        if (!$record) return [];
                                        return \App\Models\ActionTicket::where('raffle_id', $record->id)
                                            ->with('user')
                                            ->get()
                                            ->mapWithKeys(function ($t) {
                                                $name = $t->user ? $t->user->name : 'Sin usuario';
                                                return [$t->id => "#{$t->ticket_number} — {$name}"];
                                            });
                                    })
                                    ->searchable()
                                    ->nullable(),
                            ])
                            ->columns(2),
                    ])
                    ->columnSpan(['lg' => 1]),
            ])
            ->columns(3);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('title')
                    ->label('Título')
                    ->searchable()
                    ->sortable()
                    ->limit(40),

                Tables\Columns\TextColumn::make('type')
                    ->label('Tipo')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'main' => 'primary',
                        'secondary' => 'warning',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'main' => 'Principal',
                        'secondary' => 'Secundario',
                    }),

                Tables\Columns\TextColumn::make('status')
                    ->label('Estado')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'draft' => 'gray',
                        'active' => 'success',
                        'completed' => 'info',
                        'cancelled' => 'danger',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'draft' => 'Borrador',
                        'active' => 'Activo',
                        'completed' => 'Completado',
                        'cancelled' => 'Cancelado',
                    }),

                Tables\Columns\TextColumn::make('winner.name')
                    ->label('Ganador')
                    ->placeholder('Sin ganador')
                    ->searchable(),

                Tables\Columns\TextColumn::make('commercial_value')
                    ->label('Valor Comercial')
                    ->numeric(decimalPlaces: 2)
                    ->prefix('₡')
                    ->sortable(),

                Tables\Columns\TextColumn::make('total_tickets')
                    ->label('Boletos Emision')
                    ->numeric()
                    ->sortable(),

                Tables\Columns\TextColumn::make('sold_tickets')
                    ->label('Vendidos')
                    ->numeric()
                    ->sortable(),

                Tables\Columns\TextColumn::make('draw_date')
                    ->label('Fecha del Sorteo')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->label('Tipo de Sorteo')
                    ->options([
                        'main' => 'Principal',
                        'secondary' => 'Secundario',
                    ]),
                Tables\Filters\SelectFilter::make('status')
                    ->label('Estado')
                    ->options([
                        'draft' => 'Borrador',
                        'active' => 'Activo',
                        'completed' => 'Completado',
                        'cancelled' => 'Cancelado',
                    ]),
            ])
            ->actions([
                Tables\Actions\Action::make('preview')
                    ->label('Previsualizar')
                    ->icon('heroicon-o-device-phone-mobile')
                    ->color('warning')
                    ->modalContent(fn (Raffle $record) => view('filament.resources.raffles.preview', ['record' => $record]))
                    ->modalSubmitAction(false)
                    ->modalCancelActionLabel('Cerrar')
                    ->slideOver(),

                Tables\Actions\Action::make('assign_winner')
                    ->label('Ganador Manual')
                    ->icon('heroicon-o-check-circle')
                    ->color('warning')
                    ->modalHeading('Asignar Ganador del Sorteo Manualmente')
                    ->modalDescription('Ingresa o selecciona la tarjeta ganadora emitida para este sorteo.')
                    ->form([
                        Forms\Components\Select::make('action_ticket_id')
                            ->label('Seleccionar Acción / Tarjeta Vendida')
                            ->helperText('Selecciona la tarjeta ganadora de la lista de emitidas')
                            ->searchable()
                            ->getSearchResultsUsing(function (Raffle $record, string $search) {
                                return \App\Models\ActionTicket::where('raffle_id', $record->id)
                                    ->where(function ($q) use ($search) {
                                        $q->where('ticket_number', 'like', "%{$search}%")
                                          ->orWhereHas('user', function ($u) use ($search) {
                                              $u->where('name', 'like', "%{$search}%")
                                                ->orWhere('email', 'like', "%{$search}%");
                                          });
                                    })
                                    ->with('user')
                                    ->limit(30)
                                    ->get()
                                    ->mapWithKeys(function ($ticket) {
                                        $userName = $ticket->user ? $ticket->user->name : 'Desconocido';
                                        return [$ticket->id => "#{$ticket->ticket_number} — {$userName} ({$ticket->rarity})"];
                                    });
                            })
                            ->getOptionLabelUsing(function ($value) {
                                $ticket = \App\Models\ActionTicket::with('user')->find($value);
                                if (!$ticket) return $value;
                                $userName = $ticket->user ? $ticket->user->name : 'Desconocido';
                                return "#{$ticket->ticket_number} — {$userName} ({$ticket->rarity})";
                            })
                            ->nullable(),

                        Forms\Components\TextInput::make('ticket_number')
                            ->label('O escribir Número de Tarjeta directamente')
                            ->placeholder('Ej: 0050 o 1250')
                            ->helperText('Si no seleccionaste de la lista arriba, puedes escribir el número directo aquí')
                            ->nullable(),
                    ])
                    ->action(function (Raffle $record, array $data) {
                        $ticketId = $data['action_ticket_id'] ?? null;
                        $numInput = trim($data['ticket_number'] ?? '');

                        $winnerTicket = null;

                        if ($ticketId) {
                            $winnerTicket = \App\Models\ActionTicket::find($ticketId);
                        } elseif ($numInput !== '') {
                            $winnerTicket = \App\Models\ActionTicket::where('raffle_id', $record->id)
                                ->where('ticket_number', $numInput)
                                ->first();
                        }

                        if (!$winnerTicket) {
                            \Filament\Notifications\Notification::make()
                                ->title('Tarjeta No Encontrada')
                                ->body('No se encontró ninguna tarjeta emitida con esa información en este sorteo.')
                                ->danger()
                                ->send();
                            return;
                        }

                        $winner = $winnerTicket->user;

                        $record->update([
                            'winner_user_id' => $winner ? $winner->id : null,
                            'winner_action_ticket_id' => $winnerTicket->id,
                            'status' => 'completed',
                        ]);

                        if ($winner) {
                            try {
                                \App\Services\FcmService::sendNotification(
                                    $winner,
                                    '¡Felicidades, eres el Ganador! 🏆',
                                    "Tu tarjeta #{$winnerTicket->ticket_number} ha ganado el sorteo mayor: {$record->title}."
                                );
                            } catch (\Exception $e) {}
                        }

                        $winnerName = $winner ? $winner->name : 'Usuario';
                        \Filament\Notifications\Notification::make()
                            ->title('Ganador Asignado Manualmente')
                            ->body("Se asignó a {$winnerName} con la Tarjeta #{$winnerTicket->ticket_number}.")
                            ->success()
                            ->send();
                    }),

                Tables\Actions\Action::make('draw_winner')
                    ->label('Sorteo Aleatorio')
                    ->icon('heroicon-o-trophy')
                    ->color('success')
                    ->requiresConfirmation()
                    ->modalHeading('¿Realizar el Sorteo Mayor Aleatorio?')
                    ->modalDescription('Se seleccionará un ganador aleatoriamente de entre todas las acciones generadas para este sorteo.')
                    ->visible(fn (Raffle $record) => $record->status === 'active')
                    ->action(function (Raffle $record) {
                        $tickets = \App\Models\ActionTicket::where('raffle_id', $record->id)->get();

                        if ($tickets->isEmpty()) {
                            \Filament\Notifications\Notification::make()
                                ->title('Error en el Sorteo')
                                ->body('No hay tiquetes de acciones emitidos para este sorteo.')
                                ->danger()
                                ->send();
                            return;
                        }

                        $winnerTicket = $tickets->random();
                        $winner = $winnerTicket->user;

                        $record->update([
                            'winner_user_id' => $winner ? $winner->id : null,
                            'winner_action_ticket_id' => $winnerTicket->id,
                            'status' => 'completed',
                        ]);

                        if ($winner) {
                            try {
                                \App\Services\FcmService::sendNotification(
                                    $winner,
                                    '¡Felicidades, eres el Ganador! 🏆',
                                    "Tu acción #{$winnerTicket->ticket_number} ganó el sorteo mayor: {$record->title}."
                                );
                            } catch (\Exception $e) {}
                        }

                        $winnerName = $winner ? $winner->name : 'Usuario';
                        \Filament\Notifications\Notification::make()
                            ->title('Sorteo Realizado')
                            ->body("El ganador es {$winnerName} (Acción: {$winnerTicket->ticket_number})")
                            ->success()
                            ->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\ListRaffles::route('/'),
            'create' => Pages\CreateRaffle::route('/create'),
            'edit' => Pages\EditRaffle::route('/{record}/edit'),
        ];
    }

    public static function getWidgets(): array
    {
        return [
            RaffleResource\Widgets\RaffleStats::class,
        ];
    }
}
