<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\WeeklyOps\WeeklyOpsCluster;
use App\Filament\Resources\TaskResource\Pages;
use App\Models\Task;
use App\Services\Audit\SuperAdminAuditLogger;
use BackedEnum;
use Filament\Actions;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Tabs as SchemaTabs;
use Filament\Schemas\Components\Tabs\Tab as SchemaTab;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Collection;
use UnitEnum;

class TaskResource extends Resource
{
    protected static ?string $model = Task::class;

    protected static ?string $cluster = WeeklyOpsCluster::class;

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-clipboard-document-check';

    protected static UnitEnum|string|null $navigationGroup = null;

    protected static ?int $navigationSort = 30;

    public static function getNavigationGroup(): UnitEnum|string|null
    {
        return __('admin.nav.curation');
    }

    public static function getNavigationLabel(): string
    {
        return __('admin.tasks.menu');
    }

    public static function form(Schema $form): Schema
    {
        return $form->schema([
            Select::make('emotion_id')
                ->relationship('emotion', 'name')
                ->getOptionLabelFromRecordUsing(fn ($record) => is_array($record->name) ? ($record->name['de'] ?? $record->name['en'] ?? __('admin.common.unnamed')) : $record->name)
                ->required()
                ->searchable()
                ->preload(),
            Select::make('event_type_id')
                ->relationship('eventType', 'name')
                ->getOptionLabelFromRecordUsing(fn ($record) => is_array($record->name) ? ($record->name['de'] ?? $record->name['en'] ?? __('admin.common.unnamed')) : $record->name)
                ->searchable()
                ->preload()
                ->label(__('admin.tasks.fields.event_type_optional')),
            SchemaTabs::make('content_tabs')
                ->label(__('admin.tasks.fields.content_localization'))
                ->tabs([
                    SchemaTab::make(__('admin.common.german'))
                        ->icon('heroicon-o-language')
                        ->schema([
                            TextInput::make('title.de')
                                ->label(__('admin.tasks.fields.title_de'))
                                ->required(),
                            MarkdownEditor::make('description.de')
                                ->label(__('admin.tasks.fields.description_de'))
                                ->columnSpanFull(),
                            MarkdownEditor::make('example_text.de')
                                ->label(__('admin.tasks.fields.example_de'))
                                ->columnSpanFull(),
                        ]),
                    SchemaTab::make(__('admin.common.english'))
                        ->icon('heroicon-o-language')
                        ->schema([
                            TextInput::make('title.en')
                                ->label(__('admin.tasks.fields.title_en'))
                                ->required(),
                            MarkdownEditor::make('description.en')
                                ->label(__('admin.tasks.fields.description_en'))
                                ->columnSpanFull(),
                            MarkdownEditor::make('example_text.en')
                                ->label(__('admin.tasks.fields.example_en'))
                                ->columnSpanFull(),
                        ]),
                ])
                ->columnSpanFull(),
            Select::make('difficulty')->label(__('admin.tasks.fields.difficulty.label'))->options([
                'easy' => __('admin.tasks.fields.difficulty.easy'),
                'medium' => __('admin.tasks.fields.difficulty.medium'),
                'hard' => __('admin.tasks.fields.difficulty.hard'),
            ])->default('easy'),
            TextInput::make('sort_order')->numeric()->default(0),
            Toggle::make('is_active')->default(true),
        ])->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('#')
                    ->sortable(),

                Tables\Columns\TextColumn::make('title')
                    ->label(__('admin.tasks.table.title'))
                    ->getStateUsing(function ($record) {
                        $value = $record->title;
                        if (is_array($value)) {
                            $loc = app()->getLocale();

                            return $value[$loc] ?? ($value['de'] ?? ($value['en'] ?? ''));
                        }

                        return (string) $value;
                    })
                    ->limit(60)
                    ->searchable(['title->de', 'title->en']),

                Tables\Columns\TextColumn::make('emotion.name')
                    ->label(__('admin.tasks.fields.emotion'))
                    ->getStateUsing(function ($record) {
                        $value = optional($record->emotion)->name;
                        if (is_array($value)) {
                            $loc = app()->getLocale();

                            return $value[$loc] ?? ($value['de'] ?? ($value['en'] ?? ''));
                        }

                        return (string) ($value ?? '');
                    })
                    ->sortable()
                    ->searchable(['emotion->name->de', 'emotion->name->en']),

                Tables\Columns\TextColumn::make('eventType.name')
                    ->label(__('admin.tasks.fields.event_type'))
                    ->getStateUsing(function ($record) {
                        $value = optional($record->eventType)->name;
                        if (is_array($value)) {
                            $loc = app()->getLocale();

                            return $value[$loc] ?? ($value['de'] ?? ($value['en'] ?? ''));
                        }

                        return (string) ($value ?? '');
                    })
                    ->toggleable(),

                Tables\Columns\TextColumn::make('difficulty')
                    ->label(__('admin.tasks.fields.difficulty.label'))
                    ->badge(),

                Tables\Columns\IconColumn::make('is_active')
                    ->label(__('admin.tasks.table.is_active'))
                    ->boolean(),

                Tables\Columns\TextColumn::make('sort_order')
                    ->label(__('admin.tasks.table.sort_order'))
                    ->sortable(),
            ])
            ->filters([])
            ->actions([
                Actions\EditAction::make()
                    ->after(fn (array $data, Task $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
                Actions\DeleteAction::make()
                    ->after(fn (Task $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'deleted',
                        $record,
                        source: static::class
                    )),
            ])
            ->bulkActions([
                Actions\DeleteBulkAction::make()
                    ->after(function (Collection $records): void {
                        $logger = app(SuperAdminAuditLogger::class);

                        foreach ($records as $record) {
                            $logger->recordModelMutation(
                                'deleted',
                                $record,
                                source: static::class
                            );
                        }
                    }),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ManageTasks::route('/'),
            'import' => Pages\ImportTasks::route('/import'),
        ];
    }
}
