<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TestCategoryResource\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 TestCategoryResource extends Resource
{
    protected static ?string $model = TestCategory::class;
    protected static ?string $navigationIcon = 'heroicon-o-tag';
    protected static ?string $navigationLabel = 'Test Categories';
    protected static ?string $navigationGroup = 'Laboratory';
    protected static ?int $navigationSort = 3;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Category Details')
                    ->schema([
                        Forms\Components\Tabs::make('Name')
                            ->tabs([
                                Forms\Components\Tabs\Tab::make('العربية')
                                    ->icon('heroicon-o-language')
                                    ->schema([
                                        Forms\Components\TextInput::make('name.ar')
                                            ->label('الاسم بالعربي')
                                            ->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\Textarea::make('description.ar')
                                            ->label('الوصف بالعربي')
                                            ->rows(3),
                                    ]),
                                Forms\Components\Tabs\Tab::make('English')
                                    ->icon('heroicon-o-language')
                                    ->schema([
                                        Forms\Components\TextInput::make('name.en')
                                            ->label('Name in English')
                                            ->maxLength(255)
                                            ->live(onBlur: true)
                                            ->afterStateUpdated(function (string $operation, $state, Forms\Set $set, Forms\Get $get) {
                                                if ($operation === 'create' && empty($get('slug'))) {
                                                    $set('slug', \Illuminate\Support\Str::slug($state));
                                                }
                                            }),
                                        Forms\Components\Textarea::make('description.en')
                                            ->label('Description in English')
                                            ->rows(3),
                                    ]),
                            ])
                            ->columnSpanFull(),

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

                        Forms\Components\TextInput::make('icon')
                            ->label('Icon (FontAwesome class)')
                            ->placeholder('fas fa-vial')
                            ->helperText('e.g., fas fa-vial, fas fa-heart, fas fa-lungs'),

                        Forms\Components\TextInput::make('sort_order')
                            ->label('Sort Order')
                            ->numeric()
                            ->default(0),

                        Forms\Components\Toggle::make('is_active')
                            ->label('Active')
                            ->default(true),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Tests in this category')
                    ->description('Select which tests belong to this category. You can also assign tests from the Tests list using bulk action «Add to category».')
                    ->schema([
                        Forms\Components\Select::make('test_ids')
                            ->label('Tests')
                            ->multiple()
                            ->options(
                                Test::orderBy('name')->get()->mapWithKeys(fn (Test $t) => [
                                    $t->id => (string) ($t->name ?? $t->code ?? ('Test #' . $t->id)),
                                ])
                            )
                            ->searchable()
                            ->preload()
                            ->dehydrated(false)
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Name')
                    ->formatStateUsing(fn ($state) => is_array($state)
                        ? ($state['ar'] ?? '') . ' / ' . ($state['en'] ?? '')
                        : $state)
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make('icon')
                    ->label('Icon')
                    ->placeholder('-'),

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

                Tables\Columns\TextColumn::make('sort_order')
                    ->label('Order')
                    ->sortable(),

                Tables\Columns\IconColumn::make('is_active')
                    ->label('Active')
                    ->boolean(),
            ])
            ->defaultSort('sort_order', 'asc')
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTestCategories::route('/'),
            'create' => Pages\CreateTestCategory::route('/create'),
            'edit' => Pages\EditTestCategory::route('/{record}/edit'),
        ];
    }
}
