<?php

namespace App\Filament\Blog\Resources;

use App\Filament\Blog\Resources\CategoryResource\Pages;
use App\Filament\Blog\Traits\HasContentEditor;
use App\Filament\Clusters\RareAdmin\RareAdminCluster;
use App\Models\BlogCategory;
use App\Services\Audit\SuperAdminAuditLogger;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\MarkdownEditor;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs as SchemaTabs;
use Filament\Schemas\Components\Tabs\Tab as SchemaTab;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Str;

class CategoryResource extends Resource
{
    use HasContentEditor;

    protected static ?string $model = BlogCategory::class;

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

    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-list-bullet';

    protected static ?string $navigationLabel = 'Kategorien';

    protected static ?string $pluralLabel = 'Kategorien';

    protected static ?string $modelLabel = 'Kategorie';

    public static function getNavigationGroup(): string
    {
        return __('admin.nav.content');
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                SchemaTabs::make('Übersetzungen')
                    ->tabs([
                        SchemaTab::make('Deutsch')
                            ->schema([
                                TextInput::make('name_de')
                                    ->label('Name')
                                    ->validationAttribute('name_de')
                                    ->live()
                                    ->afterStateUpdated(function (Get $get, Set $set, ?string $state) {
                                        if (($get('slug') ?? '') !== Str::slug($state)) {
                                            return;
                                        }

                                        $set('slug', Str::slug($state));
                                    }),
                                MarkdownEditor::make('description_de')
                                    ->label('Beschreibung')
                                    ->validationAttribute('description_de'),
                            ]),
                        SchemaTab::make('Englisch')
                            ->schema([
                                TextInput::make('name_en')
                                    ->label('Name'),
                                MarkdownEditor::make('description_en')
                                    ->label('Beschreibung'),
                            ]),
                    ]),
                TextInput::make('slug')
                    ->label('Slug')
                    ->required()
                    ->unique(BlogCategory::class, 'slug', ignoreRecord: true),
                Section::make('Sichtbarkeit')
                    ->schema([
                        Toggle::make('is_visible')
                            ->label('Sichtbar für Gäste')
                            ->default(true),
                    ]),
                Section::make('Metadaten')
                    ->schema([
                        TextEntry::make('created_at')
                            ->label('Erstellt am')
                            ->default('—')
                            ->state(fn (?BlogCategory $record) => $record?->created_at?->diffForHumans()),
                        TextEntry::make('updated_at')
                            ->label('Zuletzt geändert')
                            ->default('—')
                            ->state(fn (?BlogCategory $record) => $record?->updated_at?->diffForHumans()),
                    ]),
            ])
            ->columns(3);
    }

    public static function mutateFormDataBeforeFill(array $data): array
    {
        $nameJson = $data['name'] ?? '[]';
        $nameArray = json_decode($nameJson, true) ?: [];
        $data['name_de'] = $nameArray['de'] ?? '';
        $data['name_en'] = $nameArray['en'] ?? '';

        $descJson = $data['description'] ?? '[]';
        $descArray = json_decode($descJson, true) ?: [];
        $data['description_de'] = $descArray['de'] ?? '';
        $data['description_en'] = $descArray['en'] ?? '';

        return $data;
    }

    public static function mutateFormDataBeforeCreate(array $data): array
    {
        $nameData = [
            'de' => $data['name_de'] ?? '',
            'en' => $data['name_en'] ?? '',
        ];
        $data['name'] = json_encode($nameData);

        $descData = [
            'de' => $data['description_de'] ?? '',
            'en' => $data['description_en'] ?? '',
        ];
        $data['description'] = json_encode($descData);

        unset($data['name_de'], $data['name_en'], $data['description_de'], $data['description_en']);

        return $data;
    }

    public static function mutateFormDataBeforeSave(array $data): array
    {
        $transformed = static::mutateFormDataBeforeCreate($data);

        return $transformed;
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->label('Name (DE)')
                    ->getStateUsing(fn ($record) => json_decode($record->name ?? '[]', true)['de'] ?? '—')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('slug')
                    ->label('Slug')
                    ->searchable()
                    ->sortable(),
                IconColumn::make('is_visible')
                    ->label('Sichtbar')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle'),
                TextColumn::make('updated_at')
                    ->label('Zuletzt geändert')
                    ->date()
                    ->sortable(),
            ])
            ->filters([
                //
            ])
            ->actions([
                EditAction::make()
                    ->after(fn (array $data, BlogCategory $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    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 getRelations(): array
    {
        return [
            //
        ];
    }

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
