<?php

namespace App\Filament\Blog\Resources;

use Illuminate\Support\Facades\Log;

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

class CategoryResource extends Resource
{
    use HasContentEditor;

    protected static ?string $model = BlogCategory::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 'Content & Bibliothek';
    }

    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'] ?? '';

        \Illuminate\Support\Facades\Log::info('BeforeFill Description Extraction:', [
            'descJson' => $descJson,
            'descArray' => $descArray,
            'description_de' => $data['description_de'],
            'description_en' => $data['description_en'],
        ]);

        return $data;
    }

    public static function mutateFormDataBeforeCreate(array $data): array
    {
        \Illuminate\Support\Facades\Log::info('mutateFormDataBeforeCreate Input Data:', ['data' => $data]);

        $nameData = [
            'de' => $data['name_de'] ?? '',
            'en' => $data['name_en'] ?? '',
        ];
        $data['name'] = json_encode($nameData);
        \Illuminate\Support\Facades\Log::info('mutateFormDataBeforeCreate Name JSON:', ['name' => $nameData]);

        $descData = [
            'de' => $data['description_de'] ?? '',
            'en' => $data['description_en'] ?? '',
        ];
        $data['description'] = json_encode($descData);
        \Illuminate\Support\Facades\Log::info('mutateFormDataBeforeCreate Description JSON:', ['description' => $descData]);

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

        \Illuminate\Support\Facades\Log::info('mutateFormDataBeforeCreate Final Data:', $data);

        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(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }

    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,
            ]);
    }
}