<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpEmployees;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpEmployees\Pages\CreateDberpEmployee;
use App\Filament\Resources\DberpEmployees\Pages\EditDberpEmployee;
use App\Filament\Resources\DberpEmployees\Pages\ListDberpEmployees;
use App\Filament\Support\DberpDeleteRecordAction;
use App\Models\DberpDepartment;
use App\Models\DberpEmployee;
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\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\Filter;
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 DberpEmployeeResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 30;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.employee_setting'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.employee_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code')),
                        TextInput::make('name')
                            ->label(__('dberp.fields.employee_name'))
                            ->required()
                            ->maxLength(120),
                        Select::make('department_id')
                            ->label(__('dberp.fields.employee_master_department'))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpEmployee) {
                                    $preserve = $livewire->getRecord()->department_id;
                                }

                                return DberpEmployee::departmentSelectOptionsForEmployeeForm(
                                    $preserve !== null ? (int) $preserve : null,
                                );
                            })
                            ->searchable()
                            ->preload()
                            ->live()
                            ->nullable(),
                        Select::make('position_id')
                            ->label(__('dberp.fields.employee_master_position'))
                            ->options(function (Get $get, $livewire): array {
                                $record = $livewire instanceof EditRecord ? $livewire->getRecord() : null;
                                $record = $record instanceof DberpEmployee ? $record : null;

                                $filterDept = filled($get('department_id')) ? (int) $get('department_id') : null;
                                $preserve = $record?->position_id !== null ? (int) $record->position_id : null;
                                $fromForm = filled($get('position_id')) ? (int) $get('position_id') : null;

                                return DberpEmployee::positionSelectOptionsForEmployeeForm(
                                    $filterDept,
                                    $preserve,
                                    $fromForm,
                                );
                            })
                            ->searchable()
                            ->preload()
                            ->nullable(),
                        TextInput::make('mobile')
                            ->label(__('dberp.fields.phone'))
                            ->maxLength(32),
                        TextInput::make('email')
                            ->label(__('dberp.fields.email'))
                            ->email()
                            ->maxLength(120),
                        TextInput::make('sort_order')
                            ->label(__('dberp.fields.sort_order'))
                            ->numeric()
                            ->default(0)
                            ->required(),
                        Toggle::make('is_salesperson')
                            ->label(__('dberp.fields.is_salesperson'))
                            ->default(true),
                        Toggle::make('is_enabled')
                            ->label(__('dberp.fields.is_enabled'))
                            ->default(true),
                        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',
                'position',
            ]))
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.employee_code'))
                    ->searchable(),
                TextColumn::make('name')
                    ->label(__('dberp.fields.employee_name'))
                    ->searchable(),
                TextColumn::make('mobile')
                    ->label(__('dberp.fields.phone'))
                    ->searchable(),
                TextColumn::make('department_display')
                    ->label(__('dberp.fields.employee_master_department'))
                    ->state(fn (DberpEmployee $record): string => $record->resolvedDepartmentLabel()),
                TextColumn::make('position_display')
                    ->label(__('dberp.fields.employee_master_position'))
                    ->state(fn (DberpEmployee $record): string => $record->resolvedPositionLabel()),
                ToggleColumn::make('is_salesperson')
                    ->label(__('dberp.fields.is_salesperson')),
                ToggleColumn::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order'))
                    ->sortable(),
            ])
            ->filters([
                Filter::make('list_keyword')
                    ->label(__('dberp.fields.keyword'))
                    ->form([
                        TextInput::make('value')
                            ->label(__('dberp.fields.keyword'))
                            ->maxLength(120),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $v = trim((string) ($data['value'] ?? ''));
                        if ($v === '') {
                            return $query;
                        }

                        $like = '%'.$v.'%';

                        return $query->where(function (Builder $builder) use ($like): void {
                            $builder
                                ->where('code', 'like', $like)
                                ->orWhere('name', 'like', $like)
                                ->orWhere('mobile', 'like', $like)
                                ->orWhere('department_name', 'like', $like)
                                ->orWhere('position_name', 'like', $like)
                                ->orWhereHas('department', fn (Builder $departmentQuery) => $departmentQuery->where('name', 'like', $like))
                                ->orWhereHas('position', fn (Builder $positionQuery) => $positionQuery->where('name', 'like', $like));
                        });
                    }),
                TernaryFilter::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled'))
                    ->trueLabel(__('dberp.options.enabled_disabled_state.enabled'))
                    ->falseLabel(__('dberp.options.enabled_disabled_state.disabled')),
                TernaryFilter::make('is_salesperson')
                    ->label(__('dberp.fields.is_salesperson'))
                    ->trueLabel(__('dberp.options.enabled_disabled_state.enabled'))
                    ->falseLabel(__('dberp.options.enabled_disabled_state.disabled')),
                SelectFilter::make('filter_department_scope')
                    ->label(__('dberp.fields.employee_master_department'))
                    ->options(fn (): array => DberpDepartment::query()
                        ->where('is_enabled', true)
                        ->orderBy('sort_order')
                        ->orderBy('id')
                        ->pluck('name', 'id')
                        ->all())
                    ->searchable(fn (): bool => DberpDepartment::query()->count() > 30)
                    ->preload()
                    ->query(function (Builder $query, array $data): Builder {
                        if (($data['value'] ?? null) === null || $data['value'] === '') {
                            return $query;
                        }

                        $id = (int) $data['value'];
                        $dept = DberpDepartment::query()->find($id);
                        if ($dept === null) {
                            return $query;
                        }

                        $name = trim((string) $dept->name);

                        return $query->where(function (Builder $outer) use ($id, $name): void {
                            $outer->where('department_id', $id)
                                ->orWhere(function (Builder $inner) use ($name): void {
                                    $inner->whereNull('department_id')
                                        ->whereNotNull('department_name')
                                        ->whereRaw('TRIM(department_name) = ?', [$name]);
                                });
                        });
                    }),
                SelectFilter::make('filter_position_scope')
                    ->label(__('dberp.fields.employee_master_position'))
                    ->options(fn (): array => DberpPosition::query()
                        ->where('is_enabled', true)
                        ->orderBy('sort_order')
                        ->orderBy('id')
                        ->pluck('name', 'id')
                        ->all())
                    ->searchable(fn (): bool => DberpPosition::query()->count() > 30)
                    ->preload()
                    ->query(function (Builder $query, array $data): Builder {
                        if (($data['value'] ?? null) === null || $data['value'] === '') {
                            return $query;
                        }

                        $id = (int) $data['value'];
                        $position = DberpPosition::query()->find($id);
                        if ($position === null) {
                            return $query;
                        }

                        $name = trim((string) $position->name);

                        return $query->where(function (Builder $outer) use ($id, $name): void {
                            $outer->where('position_id', $id)
                                ->orWhere(function (Builder $inner) use ($name): void {
                                    $inner->whereNull('position_id')
                                        ->whereNotNull('position_name')
                                        ->whereRaw('TRIM(position_name) = ?', [$name]);
                                });
                        });
                    }),
            ])
            ->recordActions([
                EditAction::make(),
                DberpDeleteRecordAction::configure(DeleteAction::make()),
            ]);
    }

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

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

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

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpEmployees::route('/'),
            'create' => CreateDberpEmployee::route('/create'),
            'edit' => EditDberpEmployee::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.employee.label');
    }

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