<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\WeeklyOps\WeeklyOpsCluster;
use App\Filament\Resources\EventTypeResource\Pages;
use App\Models\EventType;
use App\Services\Audit\SuperAdminAuditLogger;
use BackedEnum;
use Filament\Actions;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
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 EventTypeResource extends Resource
{
    protected static ?string $model = EventType::class;

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

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

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

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

    protected static ?int $navigationSort = 20;

    public static function form(Schema $form): Schema
    {
        return $form->schema([
            SchemaTabs::make('name_tabs')
                ->label(__('admin.event_types.sections.name_localization'))
                ->tabs([
                    SchemaTab::make(__('admin.common.german'))
                        ->icon('heroicon-o-language')
                        ->schema([
                            TextInput::make('name.de')
                                ->label(__('admin.event_types.fields.name_de'))
                                ->required(),
                        ]),
                    SchemaTab::make(__('admin.common.english'))
                        ->icon('heroicon-o-language')
                        ->schema([
                            TextInput::make('name.en')
                                ->label(__('admin.event_types.fields.name_en'))
                                ->required(),
                        ]),
                ]),
            TextInput::make('slug')->label(__('admin.event_types.fields.slug'))->required()->unique(ignoreRecord: true),
            TextInput::make('icon')->label(__('admin.event_types.fields.icon'))->maxLength(64),
            KeyValue::make('settings')->label(__('admin.event_types.fields.settings'))->keyLabel(__('admin.common.key'))->valueLabel(__('admin.common.value')),
            Select::make('emotions')
                ->label(__('admin.event_types.fields.emotions'))
                ->multiple()
                ->searchable()
                ->preload()
                ->relationship('emotions', '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.event_types.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('slug')
                    ->label(__('admin.event_types.table.slug'))
                    ->searchable(),

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

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('admin.event_types.table.created_at'))
                    ->since(),
            ])
            ->filters([])
            ->actions([
                Actions\EditAction::make()
                    ->after(fn (array $data, EventType $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\ManageEventTypes::route('/'),
        ];
    }
}
