<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PageResource\Pages;
use App\Models\Page;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Resources\Concerns\Translatable;
use Illuminate\Database\Eloquent\Builder;

class PageResource extends Resource
{
    use Translatable;
    protected static ?string $model = Page::class;
    protected static ?string $navigationIcon = 'heroicon-o-document-text';
    protected static ?string $navigationGroup = 'المحتوى';
    protected static ?string $navigationLabel = 'الصفحات';
    protected static ?string $modelLabel = 'صفحة';
    protected static ?string $pluralModelLabel = 'الصفحات';
    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                // Global CSS for Builder Distinction - Moving outside Split to avoid layout corruption
                Forms\Components\Placeholder::make('builder_distinction_styles')
                    ->label('')
                    ->content(new \Illuminate\Support\HtmlString('
                        <style>
                            /* CLEANER BUILDER DISTINCTION */
                            .fi-fo-builder {
                                counter-reset: prisma-section-counter;
                                padding: 20px 0 !important;
                            }
                            .fi-fo-builder > div > ul > li,
                            .fi-fo-builder-item,
                            [data-block-id] {
                                counter-increment: prisma-section-counter;
                                margin-bottom: 40px !important;
                                border: 1px solid #e2e8f0 !important;
                                border-left-width: 8px !important; /* Thick side indicator */
                                border-radius: 12px !important;
                                overflow: visible !important;
                                transition: all 0.2s ease !important;
                                background: #fff !important;
                                position: relative !important;
                                box-shadow: 0 1px 3px rgba(0,0,0,0.1) !important;
                            }
                            /* Subtle Section numbering in header */
                            .fi-fo-builder-item-header-label::before {
                                content: "#" counter(prisma-section-counter) " - ";
                                font-weight: 900;
                                color: #64748b;
                                margin-left: 5px;
                            }
                            /* LIGHTER ALTERNATING COLORS */
                            .fi-fo-builder-item:nth-child(odd) {
                                border-left-color: #3b82f6 !important; /* Blue indicator */
                            }
                            .fi-fo-builder-item:nth-child(odd) > div:first-child {
                                background: #f8faff !important;
                            }
                            .fi-fo-builder-item:nth-child(even) {
                                border-left-color: #10b981 !important; /* Green indicator */
                            }
                            .fi-fo-builder-item:nth-child(even) > div:first-child {
                                background: #f7fee7 !important;
                            }
                            /* CLEANER HOVER */
                            .fi-fo-builder-item:hover {
                                border-color: #cbd5e1 !important;
                                border-left-width: 12px !important;
                                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1) !important;
                            }
                            /* Ensure controls are not hidden */
                            .fi-fo-builder-item-header-actions {
                                opacity: 1 !important;
                                z-index: 10 !important;
                            }
                        </style>
                    '))
                    ->columnSpanFull(),

                Forms\Components\Split::make([
                    // Left side - Form fields (narrow so preview is wide)
                    Forms\Components\Tabs::make('الصفحة')
                        ->grow(false)
                        ->extraAttributes(['class' => '!min-w-[320px] !max-w-[420px] shrink-0'])
                        ->tabs([
                            Forms\Components\Tabs\Tab::make('المحتوى')
                                ->icon('heroicon-o-document')
                                ->schema([
                                    Forms\Components\TextInput::make('title')
                                        ->label('عنوان الصفحة')
                                        ->required()
                                        ->maxLength(255)
                                        ->live(debounce: 700)
                                        ->afterStateUpdated(function (string $operation, $state, Forms\Set $set) {
                                            if ($operation === 'create') {
                                                $set('slug', \Illuminate\Support\Str::slug($state));
                                            }
                                        }),
                                    
                                    Forms\Components\TextInput::make('slug')
                                        ->label('الرابط (Slug)')
                                        ->required()
                                        ->unique(ignoreRecord: true)
                                        ->maxLength(255)
                                        ->live(onBlur: true)
                                        ->helperText('رابط الصفحة في المتصفح'),
                                    

                                    Forms\Components\Section::make('صفحة HTML كاملة (اختياري)')
                                        ->schema([
                                            Forms\Components\Textarea::make('custom_html')
                                                ->label('كود HTML')
                                                ->rows(10)
                                                ->placeholder('أدخل الكود هنا...')
                                                ->hint('سيتم عرض هذا المحتوى بدلاً من الأقسام المذكورة أدناه.')
                                                ->live(debounce: 1000),
                                        ])
                                        ->collapsible()
                                        ->collapsed(),
                                    Forms\Components\Fieldset::make('أقسام الصفحة')
                                        ->schema([
                                            Forms\Components\Builder::make('content')
                                                ->label('أقسام الصفحة')
                                                ->helperText('إضافة قسم ثم كتابة المحتوى بالعربية والإنجليزية في المكانين المخصصين داخل كل قسم.')
                                                ->blocks([
                                                    // Prisma Design Blocks
                                                    \App\Filament\Blocks\PrismaHeroBlock::make(),
                                                    \App\Filament\Blocks\PrismaHeroGridBlock::make(),
                                                    \App\Filament\Blocks\PrismaCategoriesBlock::make(),
                                                    \App\Filament\Blocks\PrismaPackagesBlock::make(),
                                                    \App\Filament\Blocks\PrismaAboutBlock::make(),
                                                    \App\Filament\Blocks\PrismaServicesBlock::make(),
                                                    \App\Filament\Blocks\PrismaFaqBlock::make(),
                                                    \App\Filament\Blocks\PrismaCtaBlock::make(),
                                                    // Generic Blocks
                                                    \App\Filament\Blocks\HeroSliderBlock::make(),
                                                    \App\Filament\Blocks\PackageGridBlock::make(),
                                                    \App\Filament\Blocks\FeaturesBlock::make(),
                                                    \App\Filament\Blocks\CtaBlock::make(),
                                                    \App\Filament\Blocks\HtmlBlock::make(),
                                                    \App\Filament\Blocks\PrismaSeparatorBlock::make(),
                                                    \App\Filament\Blocks\CustomFormBlock::make(),
                                                ])
                                                ->collapsible()
                                                ->blockNumbers(false)
                                                ->addActionLabel('إضافة قسم')
                                                ->extraAttributes([
                                                    'class' => 'prisma-builder-container',
                                                    'style' => 'gap: 20px; display: flex; flex-direction: column;',
                                                ])
                                                ->columnSpanFull(),
                                        ]),
                                ]),

                            Forms\Components\Tabs\Tab::make('SEO')
                                ->icon('heroicon-o-magnifying-glass')
                                ->schema([
                                    Forms\Components\TextInput::make('meta_title')
                                        ->label('عنوان SEO')
                                        ->maxLength(70)
                                        ->placeholder('اترك فارغاً لاستخدام عنوان الصفحة'),
                                    
                                    Forms\Components\Textarea::make('meta_description')
                                        ->label('وصف SEO')
                                        ->rows(3)
                                        ->maxLength(160),
                                    
                                    Forms\Components\TagsInput::make('meta_keywords')
                                        ->label('الكلمات المفتاحية')
                                        ->separator(','),
                                ]),

                            Forms\Components\Tabs\Tab::make('الإعدادات')
                                ->icon('heroicon-o-cog')
                                ->schema([
                                    Forms\Components\Toggle::make('is_published')
                                        ->label('منشور')
                                        ->default(true)
                                        ->helperText('الصفحة تظهر للزوار فقط عندما تكون «منشور». إذا ظهرت 404 بعد إنشاء الصفحة تأكد أن هذا الخيار مفعّل.'),
                                    
                                    Forms\Components\Toggle::make('is_homepage')
                                        ->label('تعيين كصفحة رئيسية')
                                        ->default(false)
                                        ->helperText('يمكن تعيين صفحة واحدة فقط كصفحة رئيسية'),
                                    
                                    Forms\Components\TextInput::make('sort_order')
                                        ->label('ترتيب العرض')
                                        ->numeric()
                                        ->default(0),
                                ]),
                        ])
                        ->columnSpan(1),
                    
                    // Right side - Live Preview (takes remaining width)
                    Forms\Components\Section::make('معاينة مباشرة')
                        ->icon('heroicon-o-eye')
                        ->grow(true)
                        ->collapsible(false)
                        ->schema([
                            Forms\Components\ViewField::make('preview')
                                ->view('filament.pages.page-preview')
                                ->label('')
                        ])
                        ->visibleOn('edit'),
                ])
                ->extraAttributes(['class' => 'page-edit-split'])
                ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('title')
                    ->label('العنوان')
                    ->searchable()
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('slug')
                    ->label('الرابط')
                    ->searchable()
                    ->copyable(),
                
                Tables\Columns\IconColumn::make('is_published')
                    ->label('منشور')
                    ->boolean(),
                
                Tables\Columns\IconColumn::make('is_homepage')
                    ->label('رئيسية')
                    ->boolean(),
                
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('آخر تعديل')
                    ->dateTime('d M, Y H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\Filter::make('published')
                    ->label('منشور فقط')
                    ->query(fn (Builder $query): Builder => $query->where('is_published', true))
                    ->toggle(),
                
                Tables\Filters\Filter::make('homepage')
                    ->label('الصفحة الرئيسية')
                    ->query(fn (Builder $query): Builder => $query->where('is_homepage', true))
                    ->toggle(),
            ])
            ->actions([
                // Tables\Actions\Action::make('visual_builder')
                //     ->label('المحرر المباشر')
                //     ->icon('heroicon-o-sparkles')
                //     ->url(fn (Page $record): string => route('admin.visual-builder', $record))
                //     ->openUrlInNewTab()
                //     ->color('success'),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('sort_order', 'asc');
    }

    public static function getRelations(): array
    {
        return [];
    }

    public static function getPages(): array
    {
        return [
            'index' => \App\Filament\Resources\PageResource\Pages\ListPages::route('/'),
            'create' => \App\Filament\Resources\PageResource\Pages\CreatePage::route('/create'),
            'edit' => \App\Filament\Resources\PageResource\Pages\EditPage::route('/{record}/edit'),
        ];
    }
}
