<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpWarehouses;

use App\Business\MasterData\Enums\WarehouseType;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\Concerns\HasDberpRegionAddress;
use App\Filament\Resources\DberpWarehouses\Pages\CreateDberpWarehouse;
use App\Filament\Resources\DberpWarehouses\Pages\EditDberpWarehouse;
use App\Filament\Resources\DberpWarehouses\Pages\ListDberpWarehouses;
use App\Models\DberpEmployee;
use App\Models\DberpWarehouse;
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\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
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 DberpWarehouseResource extends Resource
{
    use HasDberpRegionAddress;
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 40;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.master_basic'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.warehouse_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code')),
                        TextInput::make('name')
                            ->label(__('dberp.fields.warehouse_name'))
                            ->required()
                            ->maxLength(120),
                        Select::make('warehouse_type')
                            ->label(__('dberp.fields.warehouse_type'))
                            ->options(WarehouseType::options())
                            ->default(WarehouseType::General->value)
                            ->required(),
                        Select::make('manager_employee_id')
                            ->label(__('dberp.fields.manager_employee'))
                            ->options(fn (): array => DberpEmployee::selectOptionsForFilament(
                                fn (Builder $q) => $q->where('is_enabled', true),
                            ))
                            ->searchable()
                            ->preload()
                            ->nullable(),
                        TextInput::make('contact_phone')
                            ->label(__('dberp.fields.contact_phone'))
                            ->maxLength(32),
                        TextInput::make('sort_order')
                            ->label(__('dberp.fields.sort_order'))
                            ->numeric()
                            ->default(0)
                            ->required(),
                        Toggle::make('is_default')
                            ->label(__('dberp.fields.is_default'))
                            ->default(false),
                        Toggle::make('is_enabled')
                            ->label(__('dberp.fields.is_enabled'))
                            ->default(true),
                    ])
                    ->columns(2),
                static::getDberpRegionAddressSection(),
                Section::make(__('dberp.sections.warehouse_setting'))
                    ->schema([
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.warehouse_code'))
                    ->searchable(),
                TextColumn::make('name')
                    ->label(__('dberp.fields.warehouse_name'))
                    ->searchable(),
                TextColumn::make('warehouse_type')
                    ->label(__('dberp.fields.warehouse_type'))
                    ->formatStateUsing(fn (?string $state): string => WarehouseType::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('manager.name')
                    ->label(__('dberp.fields.manager_employee')),
                ...static::getDberpRegionAddressTableColumns(),
                ToggleColumn::make('is_default')
                    ->label(__('dberp.fields.is_default')),
                ToggleColumn::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order'))
                    ->sortable(),
            ])
            ->filters([
                ...static::getDberpRegionCountryFilters(),
                TernaryFilter::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                TernaryFilter::make('is_default')
                    ->label(__('dberp.fields.is_default')),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make(),
            ]);
    }

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

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

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

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

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

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

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

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['manager', 'region']);
    }

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