<?php

namespace App\Filament\Tenant\Resources;

use App\Filament\Tenant\Resources\TaskResource\Pages;
use App\Models\Event;
use App\Models\Task;
use App\Support\TenantOnboardingState;
use BackedEnum;
use Filament\Facades\Filament;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Tabs as SchemaTabs;
use Filament\Schemas\Components\Tabs\Tab as SchemaTab;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Actions;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

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

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

    protected static ?int $navigationSort = 40;

    public static function shouldRegisterNavigation(): bool
    {
        return TenantOnboardingState::completed();
    }

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

    public static function form(Schema $form): Schema
    {
        $tenantId = Auth::user()?->tenant_id;

        return $form->schema([
            Select::make('emotion_id')
                ->relationship('emotion', 'name')
                ->required()
                ->searchable()
                ->preload(),
            Select::make('event_type_id')
                ->relationship('eventType', '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),
            Select::make('assigned_events')
                ->label(__('admin.tasks.fields.events'))
                ->multiple()
                ->relationship(
                    'assignedEvents',
                    'name',
                    fn (Builder $query) => $tenantId
                        ? $query->where('tenant_id', $tenantId)
                        : $query
                )
                ->searchable()
                ->preload()
                ->getOptionLabelFromRecordUsing(fn (Event $record) => $record->name)
                ->helperText(__('admin.tasks.fields.events_helper')),
        ])->columns(2);
    }

    public static function table(Table $table): Table
    {
        $tenantId = Auth::user()?->tenant_id;

        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'))
                    ->toggleable(),
                Tables\Columns\TextColumn::make('eventType.name')
                    ->label(__('admin.tasks.fields.event_type'))
                    ->toggleable(),
                Tables\Columns\TextColumn::make('assignedEvents.name')
                    ->label(__('admin.tasks.table.events'))
                    ->badge()
                    ->separator(', ')
                    ->limitList(2),
                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(),
                Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Actions\DeleteBulkAction::make(),
            ])
            ->modifyQueryUsing(function (Builder $query) use ($tenantId) {
                if (! $tenantId) {
                    return $query;
                }

                $query->forTenant($tenantId);

                return $query;
            });
    }

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

    public static function scopeEloquentQueryToTenant(Builder $query, ?Model $tenant): Builder
    {
        $tenant ??= Filament::getTenant();

        if (! $tenant) {
            return $query;
        }

        return $query->where(function (Builder $innerQuery) use ($tenant) {
            $innerQuery->whereNull('tenant_id')
                ->orWhere('tenant_id', $tenant->getKey());
        });
    }
}
