<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PackageResource\Pages;
use App\Models\Package;
use App\Models\TestCategory;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class PackageResource extends Resource
{
    protected static ?string $model = Package::class;
    protected static ?string $navigationIcon = 'heroicon-o-beaker';
    protected static ?string $navigationGroup = 'Laboratory';
    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Tabs::make('Package')
                    ->tabs([
                        // ── Tab 1: General Info ──
                        Forms\Components\Tabs\Tab::make('General Info')
                            ->icon('heroicon-o-information-circle')
                            ->schema([
                                Forms\Components\TextInput::make('name')
                                    ->label('Package Name (Arabic)')
                                    ->required()
                                    ->maxLength(255)
                                    ->live(onBlur: true)
                                    ->afterStateUpdated(function (string $operation, $state, Forms\Set $set) {
                                        if ($operation === 'create') {
                                            $set('slug', \Illuminate\Support\Str::slug($state));
                                        }
                                    }),

                                Forms\Components\TextInput::make('name_translations.en')
                                    ->label('Package Name (English)')
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('slug')
                                    ->label('URL Slug')
                                    ->required()
                                    ->unique(ignoreRecord: true)
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('badge_text')
                                    ->label('Badge Text (Arabic)')
                                    ->placeholder('e.g., عرض خاص')
                                    ->maxLength(50),

                                Forms\Components\TextInput::make('badge_text_translations.en')
                                    ->label('Badge Text (English)')
                                    ->placeholder('e.g., Special Offer')
                                    ->maxLength(50),

                                Forms\Components\TextInput::make('estimated_time')
                                    ->label('Estimated Time')
                                    ->placeholder('e.g., 24 ساعة'),

                                Forms\Components\FileUpload::make('image')
                                    ->label('Package Image')
                                    ->image()
                                    ->directory('packages')
                                    ->maxSize(2048)
                                    ->columnSpanFull(),

                                Forms\Components\TextInput::make('icon')
                                    ->label('Icon Class')
                                    ->placeholder('fas fa-vial')
                                    ->helperText('FontAwesome icon class'),
                            ])
                            ->columns(2),

                        // ── Tab 2: Pricing ──
                        Forms\Components\Tabs\Tab::make('Pricing')
                            ->icon('heroicon-o-currency-dollar')
                            ->schema([
                                Forms\Components\TextInput::make('price')
                                    ->label('Regular Price (SAR)')
                                    ->numeric()
                                    ->prefix('SAR')
                                    ->required()
                                    ->maxValue(999999.99),

                                Forms\Components\TextInput::make('sale_price')
                                    ->label('Sale Price (SAR)')
                                    ->numeric()
                                    ->prefix('SAR')
                                    ->maxValue(999999.99)
                                    ->helperText('Leave empty for no discount'),

                                Forms\Components\TextInput::make('non_saudi_price')
                                    ->label('Non-Saudi Price (SAR)')
                                    ->numeric()
                                    ->prefix('SAR')
                                    ->maxValue(999999.99)
                                    ->helperText('Optional price for non-Saudis'),
                            ])
                            ->columns(2),

                        // ── Tab 3: Content (العربية) ──
                        Forms\Components\Tabs\Tab::make('المحتوى (عربي)')
                            ->icon('heroicon-o-language')
                            ->schema([
                                Forms\Components\Textarea::make('short_description')
                                    ->label('الوصف القصير')
                                    ->rows(2)
                                    ->maxLength(500)
                                    ->helperText('يظهر في قائمة الباقات')
                                    ->extraAttributes(['dir' => 'rtl']),

                                Forms\Components\RichEditor::make('description')
                                    ->label('الوصف الكامل')
                                    ->toolbarButtons(['bold', 'italic', 'link', 'bulletList', 'orderedList', 'h2', 'h3'])
                                    ->columnSpanFull(),

                                Forms\Components\Section::make('معلومات العينة')
                                    ->schema([
                                        Forms\Components\TextInput::make('sample_type')
                                            ->label('نوع العينة')
                                            ->placeholder('عينة دم'),

                                        Forms\Components\TextInput::make('collection_method')
                                            ->label('طريقة الأخذ')
                                            ->placeholder('سحب دم وريدي'),

                                        Forms\Components\Textarea::make('fasting_instructions')
                                            ->label('تعليمات الصيام')
                                            ->placeholder('الصيام 8-12 ساعة مفضل')
                                            ->rows(2)
                                            ->columnSpanFull(),
                                    ])
                                    ->columns(2)
                                    ->collapsible(),

                                Forms\Components\RichEditor::make('preparation_instructions')
                                    ->label('تعليمات التحضير')
                                    ->toolbarButtons(['bold', 'italic', 'bulletList', 'orderedList'])
                                    ->columnSpanFull(),
                            ]),

                        // ── Tab 4: Content (English) ──
                        Forms\Components\Tabs\Tab::make('Content (English)')
                            ->icon('heroicon-o-language')
                            ->schema([
                                Forms\Components\Textarea::make('short_description_translations.en')
                                    ->label('Short Description')
                                    ->rows(2)
                                    ->maxLength(500),

                                Forms\Components\RichEditor::make('description_translations.en')
                                    ->label('Full Description')
                                    ->toolbarButtons(['bold', 'italic', 'link', 'bulletList', 'orderedList', 'h2', 'h3'])
                                    ->columnSpanFull(),

                                Forms\Components\Textarea::make('fasting_instructions_translations.en')
                                    ->label('Fasting Instructions (English)')
                                    ->rows(2)
                                    ->columnSpanFull(),

                                Forms\Components\RichEditor::make('preparation_instructions_translations.en')
                                    ->label('Preparation Instructions')
                                    ->toolbarButtons(['bold', 'italic', 'bulletList', 'orderedList'])
                                    ->columnSpanFull(),
                            ]),

                        // ── Tab 5: Tests ──
                        Forms\Components\Tabs\Tab::make('Tests')
                            ->icon('heroicon-o-beaker')
                            ->schema([
                                Forms\Components\Select::make('tests_display_mode')
                                    ->label('How to organize tests')
                                    ->options([
                                        'sections' => 'Group by categories/sections (custom section names + tests per section)',
                                        'flat'     => 'Flat list of tests only (no categories/sections)',
                                    ])
                                    ->default('sections')
                                    ->live()
                                    ->dehydrated(false)
                                    ->helperText('Choose whether the package shows tests grouped by sections/categories or a single list of tests.'),

                                Forms\Components\Select::make('tests')
                                    ->label('Tests (flat list)')
                                    ->relationship('tests', 'name')
                                    ->getOptionLabelFromRecordUsing(fn ($record) => (string) ($record->name ?? $record->code ?? ('Test #' . $record->id)))
                                    ->multiple()
                                    ->searchable()
                                    ->preload()
                                    ->visible(fn (Forms\Get $get) => ($get('tests_display_mode') ?? 'sections') === 'flat')
                                    ->helperText('Select all tests included in this package. Used when "Flat list" is selected above.')
                                    ->columnSpanFull(),

                                Forms\Components\Repeater::make('sections')
                                    ->label('Categories & tests (each section = one category with its tests)')
                                    ->relationship('sections')
                                    ->visible(fn (Forms\Get $get) => ($get('tests_display_mode') ?? 'sections') === 'sections')
                                    ->schema([
                                        Forms\Components\Select::make('test_category_id')
                                            ->label('Category')
                                            ->options(
                                                \App\Models\TestCategory::orderBy('sort_order')->get()->mapWithKeys(function ($c) {
                                                    $label = is_array($c->name)
                                                        ? ($c->name['ar'] ?? $c->name['en'] ?? '')
                                                        : (string) ($c->name ?? '');
                                                    return [$c->id => $label ?: 'Unnamed'];
                                                })
                                            )
                                            ->searchable()
                                            ->preload()
                                            ->live()
                                            ->afterStateUpdated(function ($state, Forms\Set $set) {
                                                if (!$state) return;
                                                $cat = \App\Models\TestCategory::find($state);
                                                if ($cat) {
                                                    $name = is_array($cat->name) ? ($cat->name['ar'] ?? $cat->name['en'] ?? '') : (string) $cat->name;
                                                    $set('name', $name);
                                                    if (is_array($cat->name) && isset($cat->name['en'])) {
                                                        $set('name_translations.en', $cat->name['en']);
                                                    }
                                                }
                                            })
                                            ->helperText('Pick a category: section name will fill from it and only tests from this category are listed below.'),

                                        Forms\Components\TextInput::make('name')
                                            ->label('Section Name (AR)')
                                            ->required()
                                            ->placeholder('e.g., وظائف الكلى'),

                                        Forms\Components\TextInput::make('name_translations.en')
                                            ->label('Section Name (EN)')
                                            ->placeholder('e.g., Kidney Functions'),

                                        Forms\Components\Select::make('bulk_category_id')
                                            ->label('Add all tests from category')
                                            ->options(
                                                \App\Models\TestCategory::orderBy('sort_order')->get()->mapWithKeys(function ($c) {
                                                    $label = is_array($c->name)
                                                        ? ($c->name['ar'] ?? $c->name['en'] ?? '')
                                                        : (string) ($c->name ?? '');
                                                    return [$c->id => $label ?: 'Unnamed'];
                                                })
                                            )
                                            ->reactive()
                                            ->afterStateUpdated(function ($state, Forms\Set $set, Forms\Get $get) {
                                                if (!$state) return;
                                                $categoryTests = \App\Models\Test::where('test_category_id', $state)->pluck('id')->toArray();
                                                $currentTests = $get('tests') ?? [];
                                                $set('tests', array_values(array_unique(array_merge($currentTests, $categoryTests))));
                                                $set('bulk_category_id', null);
                                            })
                                            ->dehydrated(false)
                                            ->searchable()
                                            ->placeholder('Optional: add all tests from a category at once')
                                            ->helperText('Optional: select a category to append all its tests to the list below.'),

                                        Forms\Components\Select::make('tests')
                                            ->label('Tests in this section')
                                            ->relationship(
                                                'tests',
                                                'name',
                                                fn ($query, Forms\Get $get) => $get('test_category_id')
                                                    ? $query->where('test_category_id', $get('test_category_id'))
                                                    : $query
                                            )
                                            ->getOptionLabelFromRecordUsing(fn ($record) => (string) ($record->name ?? $record->code ?? ('Test #' . $record->id)))
                                            ->multiple()
                                            ->searchable()
                                            ->preload()
                                            ->helperText('Select tests for this section. If a category is chosen above, only tests from that category are shown.')
                                            ->createOptionForm([
                                                Forms\Components\TextInput::make('name')
                                                    ->label('Test Name (AR)')
                                                    ->required(),
                                                Forms\Components\TextInput::make('name_translations.en')
                                                    ->label('Test Name (EN)'),
                                                Forms\Components\TextInput::make('code')
                                                    ->label('Test Code'),
                                                Forms\Components\Select::make('test_category_id')
                                                    ->relationship('category', 'name')
                                                    ->getOptionLabelFromRecordUsing(fn ($record) => is_array($record->name)
                                                        ? ($record->name['ar'] ?? $record->name['en'] ?? '') ?: 'Unnamed'
                                                        : (string) ($record->name ?? 'Unnamed'))
                                                    ->label('Category'),
                                                Forms\Components\TextInput::make('price')
                                                    ->numeric()
                                                    ->label('Price'),
                                            ])
                                            ->columnSpanFull(),
                                    ])
                                    ->orderable('sort_order')
                                    ->defaultItems(1)
                                    ->collapsible()
                                    ->itemLabel(function (array $state): string {
                                        $catId = $state['test_category_id'] ?? null;
                                        $catName = $catId ? (function () use ($catId) {
                                            $c = \App\Models\TestCategory::find($catId);
                                            if (!$c) return null;
                                            return is_array($c->name) ? ($c->name['ar'] ?? $c->name['en'] ?? '') : (string) $c->name;
                                        })() : null;
                                        $sectionName = is_array($state['name'] ?? null)
                                            ? ($state['name']['ar'] ?? $state['name']['en'] ?? '')
                                            : (string) ($state['name'] ?? '');
                                        $testsCount = isset($state['tests']) ? count((array) $state['tests']) : 0;
                                        if ($catName && $sectionName) {
                                            return "{$catName}: {$sectionName} ({$testsCount} tests)";
                                        }
                                        if ($catName) {
                                            return "{$catName} ({$testsCount} tests)";
                                        }
                                        return $sectionName ? "{$sectionName} ({$testsCount} tests)" : 'New Section';
                                    })
                                    ->columnSpanFull(),

                                Forms\Components\Repeater::make('features')
                                    ->label('Additional Features / Points')
                                    ->schema([
                                        Forms\Components\TextInput::make('feature')
                                            ->label('Feature')
                                            ->required()
                                            ->maxLength(255)
                                            ->placeholder('e.g., Home Sample Collection'),
                                    ])
                                    ->collapsible()
                                    ->collapsed()
                                    ->itemLabel(fn (array $state): ?string => $state['feature'] ?? 'New Feature')
                                    ->addActionLabel('Add Feature')
                                    ->columnSpanFull(),
                            ]),

                        // ── Tab 6: SEO ──
                        Forms\Components\Tabs\Tab::make('SEO')
                            ->icon('heroicon-o-magnifying-glass')
                            ->schema([
                                Forms\Components\TextInput::make('meta_title')
                                    ->label('Meta Title (AR)')
                                    ->maxLength(70),

                                Forms\Components\TextInput::make('meta_title_translations.en')
                                    ->label('Meta Title (EN)')
                                    ->maxLength(70),

                                Forms\Components\Textarea::make('meta_description')
                                    ->label('Meta Description (AR)')
                                    ->rows(3)
                                    ->maxLength(160),

                                Forms\Components\Textarea::make('meta_description_translations.en')
                                    ->label('Meta Description (EN)')
                                    ->rows(3)
                                    ->maxLength(160),

                                Forms\Components\TagsInput::make('meta_keywords')
                                    ->label('Meta Keywords')
                                    ->separator(','),
                            ])
                            ->columns(2),

                        // ── Tab 7: Settings ──
                        Forms\Components\Tabs\Tab::make('Settings')
                            ->icon('heroicon-o-cog')
                            ->schema([
                                Forms\Components\Toggle::make('is_active')
                                    ->label('Active')
                                    ->default(true)
                                    ->helperText('Only active packages are visible on the website'),

                                Forms\Components\Toggle::make('is_featured')
                                    ->label('Featured')
                                    ->default(false)
                                    ->helperText('Show in featured packages section'),

                                Forms\Components\Toggle::make('is_draft')
                                    ->label('Save as Draft')
                                    ->default(false)
                                    ->helperText('Drafts are not visible on the website. Use Preview to check before publishing.'),

                                Forms\Components\Select::make('custom_form_id')
                                    ->label('نموذج الحجز (اختياري)')
                                    ->relationship('customForm', 'name', fn ($query) => $query->where('is_active', true))
                                    ->searchable()
                                    ->preload()
                                    ->helperText('اختر النموذج المخصص الذي سيظهر في صفحة الباقة بدلاً من النموذج الافتراضي.'),

                                Forms\Components\TextInput::make('sort_order')
                                    ->label('Sort Order')
                                    ->numeric()
                                    ->default(0),
                            ])
                            ->columns(2),
                    ])
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('image')
                    ->label('Image')
                    ->circular()
                    ->defaultImageUrl(url('/images/default-package.png')),

                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable()
                    ->weight('font-bold'),

                Tables\Columns\TextColumn::make('price')
                    ->money('SAR')
                    ->sortable(),

                Tables\Columns\TextColumn::make('sale_price')
                    ->money('SAR')
                    ->sortable()
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('non_saudi_price')
                    ->label('Non-Saudi Price')
                    ->money('SAR')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('tests_count')
                    ->label('Tests')
                    ->counts('tests')
                    ->badge()
                    ->color('success'),

                Tables\Columns\IconColumn::make('is_active')
                    ->label('Active')
                    ->boolean(),

                Tables\Columns\IconColumn::make('is_featured')
                    ->label('Featured')
                    ->boolean(),

                Tables\Columns\IconColumn::make('is_draft')
                    ->label('Draft')
                    ->boolean()
                    ->trueIcon('heroicon-o-pencil-square')
                    ->falseIcon('heroicon-o-check-circle')
                    ->trueColor('warning')
                    ->falseColor('success'),

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Last Modified')
                    ->dateTime('M d, Y')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\Filter::make('active')
                    ->query(fn ($query) => $query->where('is_active', true))
                    ->toggle(),

                Tables\Filters\Filter::make('featured')
                    ->query(fn ($query) => $query->where('is_featured', true))
                    ->toggle(),

                Tables\Filters\Filter::make('drafts')
                    ->query(fn ($query) => $query->where('is_draft', true))
                    ->toggle(),
            ])
            ->actions([
                Tables\Actions\Action::make('preview')
                    ->label('Preview')
                    ->icon('heroicon-o-eye')
                    ->url(fn (Package $record): string => route('package.show', $record->slug))
                    ->openUrlInNewTab(),
                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\PackageResource\Pages\ListPackages::route('/'),
            'create' => \App\Filament\Resources\PackageResource\Pages\CreatePackage::route('/create'),
            'edit' => \App\Filament\Resources\PackageResource\Pages\EditPackage::route('/{record}/edit'),
        ];
    }
}
