<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpInventoryExceptions;

use App\Business\Inventory\Enums\InventoryExceptionStatus;
use App\Business\Inventory\Enums\InventoryExceptionType;
use App\Business\Inventory\InventoryExceptionService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpInventoryExceptions\Pages\EditDberpInventoryException;
use App\Filament\Resources\DberpInventoryExceptions\Pages\ListDberpInventoryExceptions;
use App\Models\DberpInventoryException;
use App\Services\DberpPermissionService;
use App\Support\DberpProductSkuSelectOptions;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpInventoryExceptionResource extends Resource implements DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'title';

    protected static ?int $navigationSort = 90;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        // 异常处理通过页头操作完成，不提供表单保存，避免误显示 Ctrl+S 保存提示。
        return false;
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.resources.inventory_exception.label'))
                ->schema([
                    TextInput::make('title')->label(__('dberp.fields.title'))->disabled(),
                    Select::make('exception_type')->label(__('dberp.fields.exception_type'))->options(InventoryExceptionType::options())->disabled(),
                    Select::make('status')
                        ->label(__('dberp.fields.exception_status'))
                        ->options(InventoryExceptionStatus::options())
                        ->disabled()
                        ->dehydrated(false),
                    DberpProductSkuSelectOptions::configureInventoryProductRelationshipSelect(
                        Select::make('product_id')->label(__('dberp.fields.product')),
                    )->disabled()->dehydrated(false),
                    Select::make('warehouse_id')->label(__('dberp.fields.warehouse'))->relationship('warehouse', 'name')->disabled()->dehydrated(false),
                    TextInput::make('severity')->label(__('dberp.fields.severity'))->disabled()->formatStateUsing(fn (?string $state): string => __('dberp.options.inventory_exception_severity')[$state] ?? (string) $state),
                    TextInput::make('description')->label(__('dberp.fields.description'))->disabled()->columnSpanFull(),
                    TextInput::make('batch.batch_no')->label(__('dberp.fields.batch_no'))->disabled()->dehydrated(false),
                    TextInput::make('serialNumber.serial_no')->label(__('dberp.fields.serial_no'))->disabled()->dehydrated(false),
                    DateTimePicker::make('occurred_at')->label(__('dberp.fields.occurred_at'))->disabled(),
                    DateTimePicker::make('resolved_at')->label(__('dberp.fields.resolved_at'))->disabled(),
                    Textarea::make('handling_remark')->label(__('dberp.fields.handling_remark'))->rows(3)->columnSpanFull(),
                ])
                ->columns(3),
        ]);
    }

    public static function getEloquentQuery(): Builder
    {
        return app(InventoryExceptionService::class)->query();
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('occurred_at', 'desc')
            ->columns([
                TextColumn::make('title')->label(__('dberp.fields.title'))->searchable(),
                TextColumn::make('exception_type')
                    ->label(__('dberp.fields.exception_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryExceptionType::options()[$state] ?? (string) $state),
                TextColumn::make('severity')
                    ->label(__('dberp.fields.severity'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.inventory_exception_severity')[$state] ?? (string) $state),
                TextColumn::make('product.name')->label(__('dberp.fields.product_name'))->searchable(),
                TextColumn::make('warehouse.name')->label(__('dberp.fields.warehouse')),
                TextColumn::make('status')
                    ->label(__('dberp.fields.exception_status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryExceptionStatus::tryFrom((string) $state)?->label() ?? (string) $state)
                    ->color(fn (?string $state): string => match ($state) {
                        InventoryExceptionStatus::Ignored->value => 'gray',
                        InventoryExceptionStatus::Resolved->value => 'success',
                        InventoryExceptionStatus::Open->value => 'warning',
                        default => 'gray',
                    }),
                TextColumn::make('occurred_at')->label(__('dberp.fields.occurred_at'))->dateTime(),
                TextColumn::make('resolved_at')->label(__('dberp.fields.resolved_at'))->dateTime(),
            ])
            ->filters([
                SelectFilter::make('status')->label(__('dberp.fields.exception_status'))->options(InventoryExceptionStatus::options()),
                SelectFilter::make('exception_type')->label(__('dberp.fields.exception_type'))->options(InventoryExceptionType::options()),
                SelectFilter::make('severity')->label(__('dberp.fields.severity'))->options(__('dberp.options.inventory_exception_severity')),
                SelectFilter::make('warehouse_id')->label(__('dberp.fields.warehouse'))->relationship('warehouse', 'name'),
                DberpProductSkuSelectOptions::configureProductRelationshipTableFilter(
                    SelectFilter::make('product_id')->label(__('dberp.fields.product')),
                ),
            ])
            ->recordActions([
                EditAction::make(),
            ]);
    }

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

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_INVENTORY_EXCEPTION,
            DberpPermissionService::HANDLE_INVENTORY_EXCEPTION,
        ]);
    }

    public static function canCreate(): bool
    {
        return false;
    }

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

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

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

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

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

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