<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSalespersons;

use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpSalespersons\Pages\CreateDberpSalesperson;
use App\Filament\Resources\DberpSalespersons\Pages\EditDberpSalesperson;
use App\Filament\Resources\DberpSalespersons\Pages\ListDberpSalespersons;
use App\Filament\Resources\DberpSalespersons\Pages\ViewDberpSalesperson;
use App\Filament\Support\DberpDeleteRecordAction;
use App\Models\DberpDepartment;
use App\Models\DberpEmployee;
use App\Models\DberpPosition;
use App\Models\DberpSalesperson;
use App\Services\DberpPermissionService;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Pages\EditRecord;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
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 DberpSalespersonResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 35;

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with([
            'employee.department',
            'employee.position',
            'department',
            'position',
        ]);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.salesperson_basic'))
                    ->schema([
                        Select::make('employee_id')
                            ->label(__('dberp.fields.linked_employee'))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpSalesperson) {
                                    $preserve = $livewire->getRecord()->employee_id;
                                }

                                return DberpSalesperson::employeeSelectOptionsForForm(
                                    $preserve !== null ? (int) $preserve : null,
                                );
                            })
                            ->searchable(fn (): bool => DberpEmployee::query()
                                ->where('is_enabled', true)
                                ->where('is_salesperson', true)
                                ->count() > 30)
                            ->preload()
                            ->live()
                            ->nullable()
                            ->afterStateUpdated(function ($state, Set $set): void {
                                if ($state === null || $state === '') {
                                    return;
                                }

                                $synced = DberpSalesperson::syncSnapshotFieldsFromEmployee([
                                    'employee_id' => (int) $state,
                                    'name' => null,
                                    'department_text' => null,
                                    'position_text' => null,
                                    'phone' => null,
                                ]);

                                $set('name', $synced['name'] ?? null);
                                $set('department_id', $synced['department_id'] ?? null);
                                $set('position_id', $synced['position_id'] ?? null);
                                $set('department_text', $synced['department_text'] ?? null);
                                $set('position_text', $synced['position_text'] ?? null);
                                $set('phone', $synced['phone'] ?? null);
                            })
                            ->helperText(__('dberp.hints.salesperson_recommend_link_employee')),
                        Placeholder::make('preview_department')
                            ->label(__('dberp.fields.employee_master_department'))
                            ->content(function (Get $get): string {
                                if (filled($get('employee_id'))) {
                                    $labels = DberpSalesperson::previewOrganizationLabelsForEmployeeId((int) $get('employee_id'));

                                    return $labels['department'];
                                }

                                if (filled($get('department_id'))) {
                                    $row = DberpDepartment::query()->find((int) $get('department_id'));

                                    return filled($row?->name) ? (string) $row->name : (string) __('dberp.labels.master_not_set');
                                }

                                $t = trim((string) ($get('department_text') ?? ''));
                                if ($t !== '') {
                                    return $t;
                                }

                                return (string) __('dberp.labels.master_not_set');
                            }),
                        Placeholder::make('preview_position')
                            ->label(__('dberp.fields.employee_master_position'))
                            ->content(function (Get $get): string {
                                if (filled($get('employee_id'))) {
                                    $labels = DberpSalesperson::previewOrganizationLabelsForEmployeeId((int) $get('employee_id'));

                                    return $labels['position'];
                                }

                                if (filled($get('position_id'))) {
                                    $row = DberpPosition::query()->find((int) $get('position_id'));

                                    return filled($row?->name) ? (string) $row->name : (string) __('dberp.labels.master_not_set');
                                }

                                $t = trim((string) ($get('position_text') ?? ''));
                                if ($t !== '') {
                                    return $t;
                                }

                                return (string) __('dberp.labels.master_not_set');
                            }),
                        Select::make('department_id')
                            ->label(__('dberp.fields.employee_master_department'))
                            ->visible(fn (Get $get): bool => ! filled($get('employee_id')))
                            ->options(function ($livewire): array {
                                $preserve = null;
                                if ($livewire instanceof EditRecord && $livewire->getRecord() instanceof DberpSalesperson) {
                                    $preserve = $livewire->getRecord()->department_id;
                                }

                                return DberpEmployee::departmentSelectOptionsForEmployeeForm(
                                    $preserve !== null ? (int) $preserve : null,
                                );
                            })
                            ->searchable(fn (): bool => DberpDepartment::query()->count() > 30)
                            ->preload()
                            ->live()
                            ->nullable(),
                        Select::make('position_id')
                            ->label(__('dberp.fields.employee_master_position'))
                            ->visible(fn (Get $get): bool => ! filled($get('employee_id')))
                            ->options(function (Get $get, $livewire): array {
                                $record = $livewire instanceof EditRecord ? $livewire->getRecord() : null;
                                $record = $record instanceof DberpSalesperson ? $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(fn (): bool => DberpPosition::query()->count() > 30)
                            ->preload()
                            ->live()
                            ->nullable(),
                        TextInput::make('name')
                            ->label(__('dberp.fields.salesperson_display_name'))
                            ->maxLength(120)
                            ->required(fn (Get $get): bool => ! filled($get('employee_id')))
                            ->disabled(fn (Get $get): bool => filled($get('employee_id')))
                            ->dehydrated(),
                        TextInput::make('department_text')
                            ->label(__('dberp.fields.employee_master_department'))
                            ->maxLength(120)
                            ->disabled(fn (Get $get): bool => filled($get('employee_id')) || filled($get('department_id')))
                            ->dehydrated(),
                        TextInput::make('position_text')
                            ->label(__('dberp.fields.employee_master_position'))
                            ->maxLength(120)
                            ->disabled(fn (Get $get): bool => filled($get('employee_id')) || filled($get('position_id')))
                            ->dehydrated(),
                        TextInput::make('phone')
                            ->label(__('dberp.fields.phone'))
                            ->maxLength(32)
                            ->disabled(fn (Get $get): bool => filled($get('employee_id')))
                            ->dehydrated(),
                        Toggle::make('is_enabled')
                            ->label(__('dberp.fields.is_enabled'))
                            ->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([
                'employee.department',
                'employee.position',
                'department',
                'position',
            ]))
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('resolved_display')
                    ->label(__('dberp.fields.salesperson_display_name'))
                    ->state(fn (DberpSalesperson $record): string => $record->resolvedDisplayName())
                    ->searchable(query: function (Builder $query, string $search): Builder {
                        $like = '%'.$search.'%';

                        return $query->where(function (Builder $builder) use ($like): void {
                            $builder
                                ->where('name', 'like', $like)
                                ->orWhere('department_text', 'like', $like)
                                ->orWhere('position_text', 'like', $like)
                                ->orWhere('phone', 'like', $like)
                                ->orWhereHas('employee', fn (Builder $employeeQuery) => $employeeQuery->where('name', 'like', $like))
                                ->orWhereHas('department', fn (Builder $departmentQuery) => $departmentQuery->where('name', 'like', $like))
                                ->orWhereHas('position', fn (Builder $positionQuery) => $positionQuery->where('name', 'like', $like));
                        });
                    }),
                TextColumn::make('employee.name')
                    ->label(__('dberp.fields.linked_employee'))
                    ->placeholder('—')
                    ->searchable(),
                TextColumn::make('resolved_department')
                    ->label(__('dberp.fields.employee_master_department'))
                    ->state(fn (DberpSalesperson $record): string => $record->resolvedDepartmentLabel()),
                TextColumn::make('resolved_position')
                    ->label(__('dberp.fields.employee_master_position'))
                    ->state(fn (DberpSalesperson $record): string => $record->resolvedPositionLabel()),
                TextColumn::make('resolved_phone')
                    ->label(__('dberp.fields.phone'))
                    ->state(fn (DberpSalesperson $record): string => $record->resolvedPhoneLabel())
                    ->toggleable(isToggledHiddenByDefault: true),
                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('name', 'like', $like)
                                ->orWhere('department_text', 'like', $like)
                                ->orWhere('position_text', 'like', $like)
                                ->orWhere('phone', 'like', $like)
                                ->orWhereHas('employee', fn (Builder $employeeQuery) => $employeeQuery->where('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.status'))
                    ->trueLabel(__('dberp.options.enabled_disabled_state.enabled'))
                    ->falseLabel(__('dberp.options.enabled_disabled_state.disabled')),
                SelectFilter::make('filter_employee_id')
                    ->label(__('dberp.fields.linked_employee'))
                    ->options(fn (): array => DberpEmployee::selectOptionsForFilament(
                        fn (Builder $q) => $q->where('is_enabled', true),
                    ))
                    ->searchable(fn (): bool => DberpEmployee::query()->where('is_enabled', true)->count() > 30)
                    ->preload()
                    ->query(fn (Builder $query, array $data): Builder => ($data['value'] ?? null)
                        ? $query->where('employee_id', (int) $data['value'])
                        : $query),
                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)
                                ->orWhereHas('employee', fn (Builder $employeeQuery): Builder => $employeeQuery->where('department_id', $id))
                                ->orWhere(function (Builder $inner) use ($name): void {
                                    $inner->whereNull('department_id')
                                        ->whereNotNull('department_text')
                                        ->whereRaw('TRIM(department_text) = ?', [$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)
                                ->orWhereHas('employee', fn (Builder $employeeQuery): Builder => $employeeQuery->where('position_id', $id))
                                ->orWhere(function (Builder $inner) use ($name): void {
                                    $inner->whereNull('position_id')
                                        ->whereNotNull('position_text')
                                        ->whereRaw('TRIM(position_text) = ?', [$name]);
                                });
                        });
                    }),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
                DberpDeleteRecordAction::configure(DeleteAction::make()),
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.salesperson_basic'))
                ->schema([
                    TextEntry::make('linked_employee')
                        ->label(__('dberp.fields.linked_employee'))
                        ->state(fn (DberpSalesperson $record): string => $record->employee?->name ?? '—'),
                    TextEntry::make('resolved_display')
                        ->label(__('dberp.fields.salesperson_display_name'))
                        ->state(fn (DberpSalesperson $record): string => $record->resolvedDisplayName()),
                    TextEntry::make('resolved_department')
                        ->label(__('dberp.fields.employee_master_department'))
                        ->state(fn (DberpSalesperson $record): string => $record->resolvedDepartmentLabel()),
                    TextEntry::make('resolved_position')
                        ->label(__('dberp.fields.employee_master_position'))
                        ->state(fn (DberpSalesperson $record): string => $record->resolvedPositionLabel()),
                    TextEntry::make('resolved_phone')
                        ->label(__('dberp.fields.phone'))
                        ->state(fn (DberpSalesperson $record): string => $record->resolvedPhoneLabel()),
                    IconEntry::make('is_enabled')
                        ->label(__('dberp.fields.is_enabled'))
                        ->boolean(),
                    TextEntry::make('sort_order')
                        ->label(__('dberp.fields.sort_order')),
                    TextEntry::make('remark')
                        ->label(__('dberp.fields.remark'))
                        ->columnSpanFull(),
                ])
                ->columns(2),
        ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpSalespersons::route('/'),
            'create' => CreateDberpSalesperson::route('/create'),
            'view' => ViewDberpSalesperson::route('/{record}'),
            'edit' => EditDberpSalesperson::route('/{record}/edit'),
        ];
    }

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

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

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

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

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

    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.salesperson.label');
    }

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