<?php

namespace App\Filament\Resources;

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

class BannerResource extends Resource
{
    protected static ?string $model = Banner::class;

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

    protected static ?string $navigationLabel = 'Banners Promocionales';

    protected static ?string $modelLabel = 'Banner Promocional';

    protected static ?string $pluralModelLabel = 'Banners Promocionales';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Detalle del Banner')
                    ->schema([
                        Forms\Components\TextInput::make('title')
                            ->label('Título del Banner')
                            ->required()
                            ->maxLength(255)
                            ->placeholder('ej: Gran Sorteo de Fin de Año'),

                        Forms\Components\TextInput::make('subtitle')
                            ->label('Subtítulo o Leyenda')
                            ->maxLength(255)
                            ->placeholder('ej: Compra tu boleto hoy y obtén un 10% extra en puntos'),

                        Forms\Components\FileUpload::make('image_path')
                            ->label('Imagen Promocional (Banner)')
                            ->disk('public')
                            ->directory('banners')
                            ->image()
                            ->required()
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Acción al Hacer Clic')
                    ->schema([
                        Forms\Components\Select::make('action_type')
                            ->label('Tipo de Acción')
                            ->options([
                                'none' => 'Sin Acción (Informativo)',
                                'url' => 'Redireccionar a Enlace Externo (URL)',
                                'raffle' => 'Vincular a un Sorteo Específico',
                            ])
                            ->default('none')
                            ->required()
                            ->live(),

                        Forms\Components\TextInput::make('action_value')
                            ->label('Dirección URL')
                            ->placeholder('https://ejemplo.com/promocion')
                            ->url()
                            ->required()
                            ->visible(fn (Forms\Get $get): bool => $get('action_type') === 'url'),

                        Forms\Components\Select::make('action_value')
                            ->label('Seleccionar Sorteo Destino')
                            ->options(fn () => Raffle::pluck('title', 'id'))
                            ->placeholder('Selecciona un sorteo activo')
                            ->required()
                            ->visible(fn (Forms\Get $get): bool => $get('action_type') === 'raffle'),
                    ]),

                Forms\Components\Section::make('Programación y Estado')
                    ->schema([
                        Forms\Components\Grid::make(4)
                            ->schema([
                                Forms\Components\Toggle::make('is_active')
                                    ->label('Activo')
                                    ->default(true)
                                    ->inline(false),

                                Forms\Components\TextInput::make('sort_order')
                                    ->label('Orden de Aparición')
                                    ->numeric()
                                    ->default(0)
                                    ->required(),

                                Forms\Components\DateTimePicker::make('start_date')
                                    ->label('Fecha Inicio de Publicación')
                                    ->native(false),

                                Forms\Components\DateTimePicker::make('end_date')
                                    ->label('Fecha Fin de Publicación')
                                    ->native(false),
                            ]),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('image_path')
                    ->label('Imagen')
                    ->disk('public')
                    ->height(60)
                    ->square(),

                Tables\Columns\TextColumn::make('title')
                    ->label('Título')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('action_type')
                    ->label('Acción')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'url' => 'primary',
                        'raffle' => 'success',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'url' => 'Enlace Web',
                        'raffle' => 'Sorteo',
                        default => 'Informativo',
                    }),

                Tables\Columns\ToggleColumn::make('is_active')
                    ->label('Activo')
                    ->sortable(),

                Tables\Columns\TextColumn::make('sort_order')
                    ->label('Orden')
                    ->numeric()
                    ->sortable(),

                Tables\Columns\TextColumn::make('start_date')
                    ->label('Desde')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),

                Tables\Columns\TextColumn::make('end_date')
                    ->label('Hasta')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Estado de Publicación')
                    ->boolean()
                    ->trueLabel('Solo Activos')
                    ->falseLabel('Solo Inactivos'),
            ])
            ->actions([
                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\ListBanners::route('/'),
            'create' => Pages\CreateBanner::route('/create'),
            'edit' => Pages\EditBanner::route('/{record}/edit'),
        ];
    }
}
