<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPositions;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpPositions\Pages\CreateDberpPosition;
use App\Filament\Resources\DberpPositions\Pages\EditDberpPosition;
use App\Filament\Resources\DberpPositions\Pages\ListDberpPositions;
use App\Models\DberpDepartment;
use App\Models\DberpPosition;
use App\Services\DberpPermissionService;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Pages\EditRecord;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpPositionResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 20;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.org_position_section'))
                    ->schema([
                        TextInput::make('name')
                            ->label(__('dberp.fields.org_position_name'))
                            ->required()
                            ->maxLength(120),
                        TextInput::make('code')
                            ->label(__('dberp.fields.org_position_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->required(fn ($livewire): bool => $livewire instanceof EditRecord),
                        Select::make('department_id')
                            ->label(__('dberp.fields.org_position_department'))
                            ->options(function ($livewire): array {
                                $record = $livewire instanceof EditRecord ? $livewire->getRecord() : null;
                                $record = $record instanceof DberpPosition ? $record : null;

                                $query = DberpDepartment::query()
                                    ->where(function (Builder $inner) use ($record): void {
                                        $inner->where('is_enabled', true);
                                        if ($record?->department_id) {
                                            $inner->orWhere(
                                                $inner->getModel()->getQualifiedKeyName(),
                                                $record->department_id,
                                            );
                                        }
                                    })
                                    ->orderBy('sort_order')
                                    ->orderBy('id');

                                return $query->pluck('name', 'id')->all();
                            })
                            ->searchable()
                            ->preload()
                            ->nullable(),
                        Toggle::make('is_enabled')
                            ->label(__('dberp.fields.status'))
                            ->default(true),
                        TextInput::make('sort_order')
                            ->label(__('dberp.fields.sort_order'))
                            ->numeric()
                            ->default(100)
                            ->required(),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn (Builder $query): Builder => $query->with('department'))
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('name')
                    ->label(__('dberp.fields.org_position_name'))
                    ->searchable(),
                TextColumn::make('code')
                    ->label(__('dberp.fields.org_position_code'))
                    ->searchable(),
                TextColumn::make('department.name')
                    ->label(__('dberp.fields.org_position_department')),
                ToggleColumn::make('is_enabled')
                    ->label(__('dberp.fields.status')),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order'))
                    ->sortable(),
                TextColumn::make('updated_at')
                    ->label(__('dberp.fields.updated_at'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                TernaryFilter::make('is_enabled')
                    ->label(__('dberp.fields.status'))
                    ->trueLabel(__('dberp.options.enabled_disabled_state.enabled'))
                    ->falseLabel(__('dberp.options.enabled_disabled_state.disabled')),
                SelectFilter::make('department_id')
                    ->label(__('dberp.fields.org_position_department'))
                    ->options(fn (): array => DberpDepartment::query()
                        ->orderBy('sort_order')
                        ->orderBy('id')
                        ->pluck('name', 'id')
                        ->all())
                    ->searchable()
                    ->preload(),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make(),
            ]);
    }

    public static function canViewAny(): bool
    {
        return static::allowsPermission(DberpPermissionService::VIEW_MASTER_POSITION);
    }

    public static function canView(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function canCreate(): bool
    {
        return static::allowsPermission(DberpPermissionService::CREATE_MASTER_POSITION);
    }

    public static function canEdit(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::EDIT_MASTER_POSITION);
    }

    public static function canDelete(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::DELETE_MASTER_POSITION);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPositions::route('/'),
            'create' => CreateDberpPosition::route('/create'),
            'edit' => EditDberpPosition::route('/{record}/edit'),
        ];
    }

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

    public static function getNavigationIcon(): string|BackedEnum|Htmlable|null
    {
        return null;
    }

    public static function getModelLabel(): string
    {
        return __('dberp.resources.position.label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('dberp.resources.position.plural');
    }
}
