<?php

namespace App\Filament\Resources\Master\SubClassifications;

use App\Enums\IsActive;
use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use App\Filament\Resources\Master\SubClassifications\Pages\ManageSubClassifications;
use App\Models\Classification;
use App\Models\SubClassification;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Grouping\Group;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use UnitEnum;

class SubClassificationResource extends Resource
{
    protected static ?string $model = SubClassification::class;

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

    protected static string|BackedEnum|null $navigationIcon = Heroicon::QueueList;

    protected static ?string $navigationLabel = 'Sub Klasifikasi';

    protected static ?int $navigationSort = 2;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $slug = 'master/sub-classifications';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Select::make('classification_id')
                    ->label('Klasifikasi')
                    ->options(Classification::query()->active()->pluck('name', 'id'))
                    ->searchable()
                    ->native(false)
                    ->required()
                    ->rules(['exists:classifications,id'])
                    ->autofocus(),

                TextInput::make('name')
                    ->label('Nama')
                    ->placeholder('Korupsi')
                    ->autocomplete(false)
                    ->required()
                    ->maxLength(50),
            ])
            ->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->label('Nama')
                    ->searchable()
                    ->sortable(),

                ToggleColumn::make('is_active')
                    ->label('Aktif?')
                    ->sortable()
                    ->getStateUsing(fn (SubClassification $record): bool => $record->is_active === IsActive::ACTIVE)
                    ->updateStateUsing(function (SubClassification $record, bool $state): void {
                        $record->is_active = $state ? IsActive::ACTIVE : IsActive::INACTIVE;
                        $record->save();

                        Notification::make()
                            ->title('Status Berubah! 🔄✨')
                            ->body('Status data berhasil diperbarui. Perubahan langsung aktif ya! 👍')
                            ->success()
                            ->send();
                    }),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn () => auth()->user()?->hasRole(RoleEnum::DEVELOPER->value)),
            ])
            ->recordActions([
                EditAction::make()
                    ->modalWidth(Width::Large),

                DeleteAction::make(),

                ForceDeleteAction::make(),

                RestoreAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Sub Klasifikasi'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::QueueList)
            ->emptyStateDescription('Setelah Anda membubat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false)
            ->groups([
                Group::make('classification.name')
                    ->label('Klasifikasi')
                    ->collapsible(),
            ])
            ->defaultGroup('classification.name');
    }

    public static function getPages(): array
    {
        return [
            'index' => ManageSubClassifications::route('/'),
        ];
    }

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