<?php

namespace App\Filament\Resources;

use App\Filament\Resources\MenuItemResource\Pages;
use App\Models\MenuItem;
use App\Models\ContentPage;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Filters\SelectFilter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

class MenuItemResource extends Resource
{
    protected static ?string $model = MenuItem::class;

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

    protected static ?string $navigationGroup = 'Content Management';

    protected static ?int $navigationSort = 1;

    protected static ?string $navigationLabel = 'Menu Items';

    protected static ?string $pluralLabel = 'Menu Items';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Basic Information')
                    ->schema([
                        Forms\Components\Grid::make(2)
                            ->schema([
                                Forms\Components\TextInput::make('title')
                                    ->required()
                                    ->maxLength(255)
                                    ->live(onBlur: true)
                                    ->afterStateUpdated(fn ($state, callable $set) => 
                                        $set('slug', Str::slug($state))),

                                Forms\Components\TextInput::make('slug')
                                    ->required()
                                    ->maxLength(255)
                                    ->unique(ignoreRecord: true)
                                    ->rules(['alpha_dash']),
                            ]),

                        Forms\Components\Textarea::make('description')
                            ->maxLength(1000)
                            ->rows(3),

                        Forms\Components\Textarea::make('keywords')
                            ->label('Keywords for text matching')
                            ->helperText('Comma-separated keywords for matching user text input')
                            ->maxLength(500)
                            ->rows(2),
                    ]),

                Forms\Components\Section::make('Menu Structure')
                    ->schema([
                        Forms\Components\Grid::make(2)
                            ->schema([
                                Forms\Components\Select::make('parent_id')
                                    ->label('Parent Menu Item')
                                    ->options(function () {
                                        return MenuItem::query()
                                            ->whereNull('parent_id')
                                            ->orWhereHas('parent', fn($q) => $q->whereNull('parent_id'))
                                            ->get()
                                            ->mapWithKeys(fn($item) => [
                                                $item->id => $item->parent_id ? 
                                                    "— {$item->title}" : $item->title
                                            ]);
                                    })
                                    ->searchable()
                                    ->placeholder('Root menu item'),

                                Forms\Components\TextInput::make('sort_order')
                                    ->numeric()
                                    ->default(0)
                                    ->helperText('Lower numbers appear first'),
                            ]),

                        Forms\Components\TextInput::make('icon')
                            ->maxLength(255)
                            ->helperText('Emoji or icon name (e.g., 📋, 🏠)'),
                    ]),

                Forms\Components\Section::make('Action Configuration')
                    ->schema([
                        Forms\Components\Select::make('action_type')
                            ->options([
                                MenuItem::ACTION_SHOW_SUBMENU => 'Show Submenu',
                                MenuItem::ACTION_SHOW_PAGE => 'Show Content Page',
                                MenuItem::ACTION_EXTERNAL_URL => 'External URL',
                                MenuItem::ACTION_CALLBACK => 'Custom Callback',
                                MenuItem::ACTION_COMMAND => 'Bot Command',
                            ])
                            ->default(MenuItem::ACTION_SHOW_SUBMENU)
                            ->live(),

                        Forms\Components\Select::make('content_page_id')
                            ->label('Content Page')
                            ->relationship('contentPage', 'title')
                            ->searchable()
                            ->visible(fn (Forms\Get $get) => 
                                $get('action_type') === MenuItem::ACTION_SHOW_PAGE),

                        Forms\Components\TextInput::make('action_data.url')
                            ->label('External URL')
                            ->url()
                            ->visible(fn (Forms\Get $get) => 
                                $get('action_type') === MenuItem::ACTION_EXTERNAL_URL),

                        Forms\Components\TextInput::make('action_data.callback')
                            ->label('Callback Data')
                            ->visible(fn (Forms\Get $get) => 
                                $get('action_type') === MenuItem::ACTION_CALLBACK),

                        Forms\Components\TextInput::make('action_data.command')
                            ->label('Bot Command')
                            ->visible(fn (Forms\Get $get) => 
                                $get('action_type') === MenuItem::ACTION_COMMAND),
                    ]),

                Forms\Components\Section::make('Visibility & Access')
                    ->schema([
                        Forms\Components\Grid::make(2)
                            ->schema([
                                Forms\Components\Toggle::make('is_active')
                                    ->default(true)
                                    ->helperText('Menu item is active and functional'),

                                Forms\Components\Toggle::make('is_visible')
                                    ->default(true)
                                    ->helperText('Menu item is visible to users'),
                            ]),

                        Forms\Components\CheckboxList::make('roles')
                            ->label('Allowed User Roles')
                            ->options([
                                'user' => 'User',
                                'admin' => 'Admin',
                                'moderator' => 'Moderator',
                            ])
                            ->helperText('Leave empty to allow all users')
                            ->columns(3),
                    ]),

                Forms\Components\Section::make('Additional Data')
                    ->schema([
                        Forms\Components\Textarea::make('metadata')
                            ->label('Metadata (JSON)')
                            ->helperText('Additional configuration data in JSON format')
                            ->rows(3),
                    ])
                    ->collapsible()
                    ->collapsed(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('title')
                    ->searchable()
                    ->sortable()
                    ->formatStateUsing(function ($record) {
                        $indent = str_repeat('— ', $record->parent_id ? 1 : 0);
                        $icon = $record->icon ? $record->icon . ' ' : '';
                        return $indent . $icon . $record->title;
                    }),

                Tables\Columns\TextColumn::make('slug')
                    ->searchable()
                    ->copyable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('parent.title')
                    ->label('Parent')
                    ->placeholder('Root')
                    ->toggleable(),

                Tables\Columns\BadgeColumn::make('action_type')
                    ->label('Action')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        MenuItem::ACTION_SHOW_SUBMENU => 'Submenu',
                        MenuItem::ACTION_SHOW_PAGE => 'Page',
                        MenuItem::ACTION_EXTERNAL_URL => 'URL',
                        MenuItem::ACTION_CALLBACK => 'Callback',
                        MenuItem::ACTION_COMMAND => 'Command',
                        default => ucfirst($state),
                    })
                    ->color(fn (string $state): string => match ($state) {
                        MenuItem::ACTION_SHOW_SUBMENU => 'gray',
                        MenuItem::ACTION_SHOW_PAGE => 'success',
                        MenuItem::ACTION_EXTERNAL_URL => 'info',
                        MenuItem::ACTION_CALLBACK => 'warning',
                        MenuItem::ACTION_COMMAND => 'danger',
                        default => 'secondary',
                    }),

                Tables\Columns\TextColumn::make('contentPage.title')
                    ->label('Content Page')
                    ->placeholder('—')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('sort_order')
                    ->sortable()
                    ->alignCenter(),

                Tables\Columns\IconColumn::make('is_active')
                    ->boolean()
                    ->trueColor('success')
                    ->falseColor('danger'),

                Tables\Columns\IconColumn::make('is_visible')
                    ->boolean()
                    ->trueColor('success')
                    ->falseColor('gray'),

                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('parent_id')
                    ->label('Parent')
                    ->options(fn () => MenuItem::whereNull('parent_id')
                        ->pluck('title', 'id')
                        ->prepend('Root Items', 'root'))
                    ->query(function (Builder $query, array $data): Builder {
                        if ($data['value'] === 'root') {
                            return $query->whereNull('parent_id');
                        }
                        return $query->where('parent_id', $data['value']);
                    }),

                SelectFilter::make('action_type')
                    ->options([
                        MenuItem::ACTION_SHOW_SUBMENU => 'Show Submenu',
                        MenuItem::ACTION_SHOW_PAGE => 'Show Page',
                        MenuItem::ACTION_EXTERNAL_URL => 'External URL',
                        MenuItem::ACTION_CALLBACK => 'Callback',
                        MenuItem::ACTION_COMMAND => 'Command',
                    ]),

                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Active Status'),

                Tables\Filters\TernaryFilter::make('is_visible')
                    ->label('Visibility'),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('sort_order')
            ->reorderable('sort_order');
    }

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

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('is_active', true)->count();
    }
}