<?php

namespace App\Filament\Resources\ContentPages;

use App\Filament\Resources\ContentPages\Pages\CreateContentPage;
use App\Filament\Resources\ContentPages\Pages\EditContentPage;
use App\Filament\Resources\ContentPages\Pages\ListContentPages;
use App\Filament\Resources\ContentPages\Pages\ViewContentPage;
use App\Models\ContentPage;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Str;

class ContentPageResource extends Resource
{
    protected static ?string $model = ContentPage::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::DocumentCheck;

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

    protected static string|\UnitEnum|null $navigationGroup = 'Platform';

    protected static ?int $navigationSort = 20;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Page content')
                    ->schema([
                        TextInput::make('title')
                            ->required()
                            ->live(onBlur: true)
                            ->afterStateUpdated(fn (Set $set, ?string $state): mixed => filled($state)
                                ? $set('slug', Str::slug($state))
                                : null)
                            ->maxLength(255),

                        TextInput::make('slug')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->rules(['alpha_dash:ascii'])
                            ->maxLength(255)
                            ->helperText('Generated public link: /pages/your-slug'),

                        Textarea::make('excerpt')
                            ->rows(3)
                            ->maxLength(500)
                            ->columnSpanFull(),

                        Textarea::make('content')
                            ->required()
                            ->rows(18)
                            ->helperText('Plain text is rendered safely. Start a paragraph with #, ##, or ### for headings.')
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                Section::make('Publishing')
                    ->schema([
                        Select::make('status')
                            ->required()
                            ->options([
                                ContentPage::STATUS_DRAFT => 'Draft',
                                ContentPage::STATUS_PUBLISHED => 'Published',
                            ])
                            ->default(ContentPage::STATUS_DRAFT)
                            ->native(false),

                        DateTimePicker::make('published_at')
                            ->helperText('Published pages are public only after this time. Leave blank to publish immediately when status is Published.'),

                        Toggle::make('show_in_footer')
                            ->label('Show in footer')
                            ->helperText('Adds this page to the public footer automatically.'),

                        TextInput::make('footer_label')
                            ->maxLength(120)
                            ->helperText('Optional shorter label used in footer.'),

                        TextInput::make('footer_sort')
                            ->integer()
                            ->default(100)
                            ->minValue(0),
                    ])
                    ->columns(2),

                Section::make('SEO')
                    ->schema([
                        TextInput::make('meta_title')
                            ->maxLength(255),

                        Textarea::make('meta_description')
                            ->rows(3)
                            ->maxLength(500)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

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

                TextColumn::make('slug')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('public_link')
                    ->label('Generated link')
                    ->state(fn (ContentPage $record): string => $record->publicUrl())
                    ->copyable()
                    ->limit(58),

                TextColumn::make('status')
                    ->badge()
                    ->sortable(),

                IconColumn::make('show_in_footer')
                    ->label('Footer')
                    ->boolean()
                    ->sortable(),

                TextColumn::make('published_at')
                    ->dateTime()
                    ->sortable(),

                TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->options([
                        ContentPage::STATUS_DRAFT => 'Draft',
                        ContentPage::STATUS_PUBLISHED => 'Published',
                    ]),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->recordUrl(fn (ContentPage $record): string => static::getUrl('view', ['record' => $record]))
            ->defaultSort('updated_at', 'desc');
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Page details')
                    ->schema([
                        TextEntry::make('title'),

                        TextEntry::make('slug')
                            ->copyable(),

                        TextEntry::make('public_url')
                            ->label('Generated public link')
                            ->state(fn (ContentPage $record): string => $record->publicUrl())
                            ->copyable(),

                        TextEntry::make('status')
                            ->badge(),

                        TextEntry::make('published_at')
                            ->dateTime()
                            ->placeholder('Not published'),

                        TextEntry::make('show_in_footer')
                            ->label('Shown in footer')
                            ->formatStateUsing(fn (bool $state): string => $state ? 'Yes' : 'No'),
                    ])
                    ->columns(3),

                Section::make('Content preview')
                    ->schema([
                        TextEntry::make('excerpt')
                            ->placeholder('No excerpt')
                            ->columnSpanFull(),

                        TextEntry::make('content')
                            ->placeholder('No content')
                            ->columnSpanFull(),
                    ]),

                Section::make('SEO')
                    ->schema([
                        TextEntry::make('meta_title')
                            ->placeholder('Uses page title'),

                        TextEntry::make('meta_description')
                            ->placeholder('No meta description'),
                    ])
                    ->columns(2),
            ]);
    }

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