<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TestResource\Pages;
use App\Models\Test;
use App\Models\TestCategory;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class TestResource extends Resource
{
    protected static ?string $model = Test::class;
    protected static ?string $navigationIcon = 'heroicon-o-beaker';
    protected static ?string $navigationLabel = 'Medical Tests';
    protected static ?string $navigationGroup = 'Laboratory';
    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Tabs::make('Test')
                    ->tabs([
                        // ── Tab 1: Basic Info ──
                        Forms\Components\Tabs\Tab::make('Basic Info')
                            ->icon('heroicon-o-information-circle')
                            ->schema([
                                Forms\Components\TextInput::make('name')
                                    ->label('Test Name (Primary)')
                                    ->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('slug')
                                    ->label('URL Slug')
                                    ->required()
                                    ->unique(ignoreRecord: true)
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('code')
                                    ->label('Test Code')
                                    ->placeholder('e.g., CBC-001')
                                    ->maxLength(50),

                                Forms\Components\Select::make('test_category_id')
                                    ->label('Category')
                                    ->relationship('category', 'name')
                                    ->getOptionLabelFromRecordUsing(fn ($record) => is_array($record->name)
                                        ? ($record->name['ar'] ?? '') . ' / ' . ($record->name['en'] ?? '')
                                        : ($record->name ?? ''))
                                    ->searchable()
                                    ->preload()
                                    ->createOptionForm([
                                        Forms\Components\TextInput::make('name.ar')
                                            ->label('الاسم بالعربي')
                                            ->required(),
                                        Forms\Components\TextInput::make('name.en')
                                            ->label('Name in English'),
                                        Forms\Components\TextInput::make('slug')
                                            ->label('Slug')
                                            ->required(),
                                    ])
                                    ->helperText('Group this test under a category (e.g., Complete Blood Count, Kidney Functions)'),
                            ])
                            ->columns(2),

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

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

                        // ── Tab 3: 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(),
                            ]),

                        // ── Tab 4: Test Details ──
                        Forms\Components\Tabs\Tab::make('Test Details')
                            ->icon('heroicon-o-clipboard-document')
                            ->schema([
                                Forms\Components\TextInput::make('normal_range')
                                    ->label('Normal Range')
                                    ->placeholder('e.g., 4.5 - 11.0 x10^9/L'),

                                Forms\Components\TextInput::make('unit')
                                    ->label('Unit of Measurement')
                                    ->placeholder('e.g., mg/dL, mmol/L'),

                                Forms\Components\TextInput::make('sample_type')
                                    ->label('Sample Type')
                                    ->placeholder('e.g., Blood, Urine'),

                                Forms\Components\TextInput::make('estimated_time')
                                    ->label('Estimated Time')
                                    ->placeholder('e.g., 2 hours'),

                                Forms\Components\TextInput::make('price')
                                    ->label('Test Price (SAR)')
                                    ->numeric()
                                    ->prefix('SAR')
                                    ->maxValue(999999.99),
                            ])
                            ->columns(2),

                        // ── Tab 5: Instructions ──
                        Forms\Components\Tabs\Tab::make('Instructions')
                            ->icon('heroicon-o-document-text')
                            ->schema([
                                Forms\Components\RichEditor::make('preparation_instructions')
                                    ->label('Preparation Instructions')
                                    ->toolbarButtons(['bold', 'italic', 'bulletList', 'orderedList'])
                                    ->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')
                                    ->maxLength(70),

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

                        // ── Tab 7: Settings ──
                        Forms\Components\Tabs\Tab::make('Settings')
                            ->icon('heroicon-o-cog')
                            ->schema([
                                Forms\Components\Toggle::make('is_active')
                                    ->label('Active')
                                    ->default(true),
                            ]),
                    ])
                    ->columnSpanFull(),
            ]);
    }

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

                Tables\Columns\TextColumn::make('category.name')
                    ->label('Category')
                    ->formatStateUsing(fn ($state) => is_array($state)
                        ? ($state['ar'] ?? $state['en'] ?? '-')
                        : ($state ?? '-'))
                    ->badge()
                    ->color('info')
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('code')
                    ->searchable()
                    ->badge()
                    ->color('gray')
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('sample_type')
                    ->searchable()
                    ->placeholder('-'),

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

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

                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\SelectFilter::make('test_category_id')
                    ->label('Category')
                    ->relationship('category', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => is_array($record->name)
                        ? ($record->name['ar'] ?? '') . ' / ' . ($record->name['en'] ?? '')
                        : $record->name)
                    ->searchable()
                    ->preload(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\BulkAction::make('add_to_category')
                        ->label('Add to category')
                        ->icon('heroicon-o-tag')
                        ->form([
                            Forms\Components\Select::make('test_category_id')
                                ->label('Category')
                                ->options(
                                    TestCategory::orderBy('sort_order')->get()->mapWithKeys(function ($c) {
                                        $label = is_array($c->name)
                                            ? ($c->name['ar'] ?? $c->name['en'] ?? '') . ' / ' . ($c->name['en'] ?? $c->name['ar'] ?? '')
                                            : (string) ($c->name ?? '');
                                        return [$c->id => $label ?: 'Unnamed'];
                                    })
                                )
                                ->required()
                                ->searchable()
                                ->preload(),
                        ])
                        ->action(function (Tables\Actions\BulkAction $action, \Illuminate\Support\Collection $records, array $data): void {
                            Test::whereIn('id', $records->pluck('id')->toArray())
                                ->update(['test_category_id' => $data['test_category_id']]);
                            \Filament\Notifications\Notification::make()
                                ->title('Tests added to category')
                                ->success()
                                ->send();
                        }),
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('name', 'asc')
            ->headerActions([
                \App\Filament\Tables\Actions\ImportTestsAction::make()
                    ->importer(\App\Filament\Imports\TestImporter::class)
                    ->label('Import Tests (CSV or Excel)'),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => \App\Filament\Resources\TestResource\Pages\ListTests::route('/'),
            'create' => \App\Filament\Resources\TestResource\Pages\CreateTest::route('/create'),
            'edit' => \App\Filament\Resources\TestResource\Pages\EditTest::route('/{record}/edit'),
        ];
    }
}
