<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ContentPageResource\Pages;
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 ContentPageResource extends Resource
{
    protected static ?string $model = ContentPage::class;

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

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

    protected static ?int $navigationSort = 2;

    protected static ?string $navigationLabel = 'Content Pages';

    protected static ?string $pluralLabel = 'Content Pages';

    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('excerpt')
                            ->maxLength(300)
                            ->rows(2)
                            ->helperText('Brief description of the page content'),

                        Forms\Components\RichEditor::make('content')
                            ->required()
                            ->toolbarButtons([
                                'bold',
                                'italic',
                                'underline',
                                'strike',
                                'bulletList',
                                'orderedList',
                                'redo',
                                'undo',
                            ])
                            ->maxLength(10000),
                    ]),

                Forms\Components\Section::make('Publishing')
                    ->schema([
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Select::make('status')
                                    ->options([
                                        ContentPage::STATUS_DRAFT => 'Draft',
                                        ContentPage::STATUS_PUBLISHED => 'Published',
                                        ContentPage::STATUS_ARCHIVED => 'Archived',
                                    ])
                                    ->default(ContentPage::STATUS_DRAFT)
                                    ->required(),

                                Forms\Components\Select::make('language')
                                    ->options([
                                        'fa' => 'Persian (فارسی)',
                                        'en' => 'English',
                                    ])
                                    ->default('fa')
                                    ->required(),

                                Forms\Components\Select::make('template')
                                    ->options([
                                        ContentPage::TEMPLATE_DEFAULT => 'Default',
                                        ContentPage::TEMPLATE_FAQ => 'FAQ',
                                        ContentPage::TEMPLATE_CONTACT => 'Contact',
                                        ContentPage::TEMPLATE_ABOUT => 'About',
                                    ])
                                    ->default(ContentPage::TEMPLATE_DEFAULT)
                                    ->required(),
                            ]),

                        Forms\Components\DateTimePicker::make('published_at')
                            ->default(now())
                            ->helperText('When this page should be published'),

                        Forms\Components\Select::make('author_id')
                            ->relationship('author', 'name')
                            ->searchable()
                            ->default(fn () => auth()->id()),
                    ])->columns(2),

                Forms\Components\Section::make('SEO & Metadata')
                    ->schema([
                        Forms\Components\TextInput::make('seo_title')
                            ->maxLength(60)
                            ->helperText('SEO title (max 60 characters)'),

                        Forms\Components\Textarea::make('seo_description')
                            ->maxLength(160)
                            ->rows(2)
                            ->helperText('SEO description (max 160 characters)'),

                        Forms\Components\TextInput::make('seo_keywords')
                            ->maxLength(255)
                            ->helperText('Comma-separated SEO keywords'),

                        Forms\Components\TextInput::make('featured_image')
                            ->url()
                            ->maxLength(500)
                            ->helperText('URL to featured image'),
                    ])
                    ->collapsible()
                    ->collapsed(),

                Forms\Components\Section::make('Related Content')
                    ->schema([
                        Forms\Components\Select::make('related_pages')
                            ->label('Related Pages')
                            ->multiple()
                            ->options(fn () => ContentPage::published()
                                ->pluck('title', 'id'))
                            ->searchable(),

                        Forms\Components\TagsInput::make('tags')
                            ->helperText('Tags for categorizing content'),
                    ])
                    ->collapsible()
                    ->collapsed(),

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

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('title')
                    ->searchable()
                    ->sortable()
                    ->weight('medium'),

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

                Tables\Columns\BadgeColumn::make('status')
                    ->color(fn (string $state): string => match ($state) {
                        ContentPage::STATUS_PUBLISHED => 'success',
                        ContentPage::STATUS_DRAFT => 'warning',
                        ContentPage::STATUS_ARCHIVED => 'danger',
                        default => 'secondary',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        ContentPage::STATUS_PUBLISHED => 'Published',
                        ContentPage::STATUS_DRAFT => 'Draft',
                        ContentPage::STATUS_ARCHIVED => 'Archived',
                        default => ucfirst($state),
                    }),

                Tables\Columns\BadgeColumn::make('language')
                    ->color('info')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'fa' => 'فارسی',
                        'en' => 'English',
                        default => strtoupper($state),
                    }),

                Tables\Columns\BadgeColumn::make('template')
                    ->color('gray')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        ContentPage::TEMPLATE_DEFAULT => 'Default',
                        ContentPage::TEMPLATE_FAQ => 'FAQ',
                        ContentPage::TEMPLATE_CONTACT => 'Contact',
                        ContentPage::TEMPLATE_ABOUT => 'About',
                        default => ucfirst($state),
                    })
                    ->toggleable(),

                Tables\Columns\TextColumn::make('author.name')
                    ->label('Author')
                    ->placeholder('—')
                    ->toggleable(),

                Tables\Columns\TextColumn::make('view_count')
                    ->label('Views')
                    ->numeric()
                    ->sortable()
                    ->alignCenter(),

                Tables\Columns\TextColumn::make('published_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->options([
                        ContentPage::STATUS_DRAFT => 'Draft',
                        ContentPage::STATUS_PUBLISHED => 'Published',
                        ContentPage::STATUS_ARCHIVED => 'Archived',
                    ]),

                SelectFilter::make('language')
                    ->options([
                        'fa' => 'Persian (فارسی)',
                        'en' => 'English',
                    ]),

                SelectFilter::make('template')
                    ->options([
                        ContentPage::TEMPLATE_DEFAULT => 'Default',
                        ContentPage::TEMPLATE_FAQ => 'FAQ',
                        ContentPage::TEMPLATE_CONTACT => 'Contact',
                        ContentPage::TEMPLATE_ABOUT => 'About',
                    ]),

                SelectFilter::make('author_id')
                    ->label('Author')
                    ->relationship('author', 'name'),

                Tables\Filters\Filter::make('published_at')
                    ->form([
                        Forms\Components\DatePicker::make('published_from'),
                        Forms\Components\DatePicker::make('published_until'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['published_from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('published_at', '>=', $date),
                            )
                            ->when(
                                $data['published_until'],
                                fn (Builder $query, $date): Builder => $query->whereDate('published_at', '<=', $date),
                            );
                    }),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListContentPages::route('/'),
            'create' => Pages\CreateContentPage::route('/create'),
            'view' => Pages\ViewContentPage::route('/{record}'),
            'edit' => Pages\EditContentPage::route('/{record}/edit'),
        ];
    }

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

    public static function getNavigationBadgeColor(): ?string
    {
        $draftCount = static::getModel()::where('status', ContentPage::STATUS_DRAFT)->count();
        return $draftCount > 0 ? 'warning' : 'success';
    }
}