<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\WeeklyOps\WeeklyOpsCluster;
use App\Filament\Resources\EmotionResource\Pages;
use App\Models\Emotion;
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 EmotionResource extends Resource
{
    protected static ?string $model = Emotion::class;

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

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-face-smile';

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

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

    protected static ?int $navigationSort = 10;

    public static function form(Schema $form): Schema
    {
        return $form->schema([
            SchemaTabs::make('content_tabs')
                ->label(__('admin.emotions.sections.content_localization'))
                ->tabs([
                    SchemaTab::make(__('admin.common.german'))
                        ->icon('heroicon-o-language')
                        ->schema([
                            TextInput::make('name.de')
                                ->label(__('admin.emotions.fields.name_de'))
                                ->required(),
                            MarkdownEditor::make('description.de')
                                ->label(__('admin.emotions.fields.description_de'))
                                ->columnSpanFull(),
                        ]),
                    SchemaTab::make(__('admin.common.english'))
                        ->icon('heroicon-o-language')
                        ->schema([
                            TextInput::make('name.en')
                                ->label(__('admin.emotions.fields.name_en'))
                                ->required(),
                            MarkdownEditor::make('description.en')
                                ->label(__('admin.emotions.fields.description_en'))
                                ->columnSpanFull(),
                        ]),
                ])
                ->columnSpanFull(),
            TextInput::make('icon')->label(__('admin.emotions.fields.icon_emoji'))->maxLength(50),
            TextInput::make('color')->maxLength(7)->helperText('#RRGGBB'),
            TextInput::make('sort_order')->numeric()->default(0),
            Toggle::make('is_active')->default(true),
            Select::make('eventTypes')
                ->label(__('admin.emotions.fields.event_types'))
                ->multiple()
                ->searchable()
                ->preload()
                ->relationship('eventTypes', 'name'),
        ])->columns(2);
    }

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

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

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

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

                Tables\Columns\TextColumn::make('icon')
                    ->label(__('admin.emotions.table.icon')),

                Tables\Columns\TextColumn::make('color')
                    ->label(__('admin.emotions.table.color')),

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

                Tables\Columns\TextColumn::make('sort_order')
                    ->label(__('admin.emotions.table.sort_order'))
                    ->sortable(),
            ])
            ->filters([])
            ->actions([
                Actions\EditAction::make()
                    ->after(fn (array $data, Emotion $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        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\ManageEmotions::route('/'),
            'import' => Pages\ImportEmotions::route('/import'),
        ];
    }
}
