<?php

namespace App\Filament\Resources;

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

class StoryResource extends Resource
{
    protected static ?string $model = Story::class;

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

    protected static ?string $navigationLabel = 'Historias / Reels';

    protected static ?string $modelLabel = 'Historia / Reel';

    protected static ?string $pluralModelLabel = 'Historias / Reels';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Detalle de la Historia')
                    ->schema([
                        Forms\Components\TextInput::make('title')
                            ->label('Título de la Historia (Opcional)')
                            ->maxLength(255)
                            ->placeholder('ej: ¡Nuevo sorteo disponible!'),

                        Forms\Components\Select::make('media_type')
                            ->label('Tipo de Multimedia')
                            ->options([
                                'image' => 'Imagen',
                                'video' => 'Video',
                            ])
                            ->default('image')
                            ->required()
                            ->live(),

                        Forms\Components\FileUpload::make('media_path')
                            ->label('Archivo Multimedia')
                            ->disk('public')
                            ->directory('stories')
                            ->acceptedFileTypes([
                                'image/jpeg', 'image/png', 'image/webp', 'image/gif',
                                'video/mp4', 'video/quicktime', 'video/x-matroska', 'video/webm'
                            ])
                            ->maxSize(51200) // 50MB max
                            ->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\TextInput::make('button_text')
                            ->label('Texto del Botón')
                            ->placeholder('ej: Ver Sorteo')
                            ->default('Ver Más')
                            ->maxLength(50)
                            ->visible(fn (Forms\Get $get): bool => $get('action_type') !== 'none'),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Programación y Estado')
                    ->schema([
                        Forms\Components\Grid::make(3)
                            ->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('expires_at')
                                    ->label('Fecha de Expiración (Opcional)')
                                    ->native(false),
                            ]),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('media_path')
                    ->label('Miniatura')
                    ->disk('public')
                    ->height(60)
                    ->square()
                    ->placeholder('Video o sin imagen'),

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

                Tables\Columns\TextColumn::make('media_type')
                    ->label('Tipo')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'video' => 'warning',
                        default => 'info',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'video' => 'Video',
                        default => 'Imagen',
                    }),

                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('expires_at')
                    ->label('Expiración')
                    ->dateTime('d/m/Y H:i')
                    ->sortable()
                    ->placeholder('Nunca'),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Estado')
                    ->boolean()
                    ->trueLabel('Solo Activas')
                    ->falseLabel('Solo Inactivas'),
            ])
            ->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\ListStories::route('/'),
            'create' => Pages\CreateStory::route('/create'),
            'edit' => Pages\EditStory::route('/{record}/edit'),
        ];
    }
}
