<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Resources\DberpInventoryRules;

use App\Business\Inventory\InventoryRuleEvaluatorService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpInventoryRules\Pages\CreateDberpInventoryRule;
use App\Filament\Resources\DberpInventoryRules\Pages\EditDberpInventoryRule;
use App\Filament\Resources\DberpInventoryRules\Pages\ListDberpInventoryRules;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Filament\Support\DberpFilamentRecordTitles;
use App\Models\DberpInventoryRule;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
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\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpInventoryRuleResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?int $navigationSort = 130;

    public static function hasRecordTitle(): bool
    {
        return true;
    }

    public static function getRecordTitle(?Model $record): string|Htmlable|null
    {
        if (! $record instanceof DberpInventoryRule) {
            return parent::getRecordTitle($record);
        }

        return DberpFilamentRecordTitles::inventoryRule($record);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.inventory_rule'))
                ->description((string) __('dberp.hints.inventory_rule_section'))
                ->schema([
                    DberpProductSkuSelectOptions::configureInventoryProductRelationshipSelect(
                        Select::make('product_id')
                            ->label(__('dberp.fields.product')),
                    )->required(),
                    Select::make('warehouse_id')
                        ->label(__('dberp.fields.warehouse'))
                        ->relationship('warehouse', 'name')
                        ->searchable()
                        ->preload()
                        ->required(),
                    DberpFilamentNumberFields::quantityInput(
                        TextInput::make('safety_stock')
                            ->label(__('dberp.fields.safety_stock'))
                            ->default(0),
                        withHelperText: false,
                        minValue: 0.0,
                    )->helperText((string) __('dberp.hints.inventory_rule_safety_stock_sync')),
                    Toggle::make('manages_batch')
                        ->label(__('dberp.fields.manages_batch'))
                        ->default(false)
                        ->helperText((string) __('dberp.hints.inventory_rule_governance_flags_follow_product')),
                    Toggle::make('manages_serial_number')
                        ->label(__('dberp.fields.manages_serial_number'))
                        ->default(false),
                    Toggle::make('manages_expiry')
                        ->label(__('dberp.fields.manages_expiry'))
                        ->default(false),
                    DberpFilamentNumberFields::quantityInput(
                        TextInput::make('reorder_point')
                            ->label(__('dberp.fields.reorder_point'))
                            ->default(0),
                        withHelperText: false,
                        minValue: 0.0,
                    )->helperText((string) __('dberp.hints.inventory_rule_reorder_replenishment')),
                    DberpFilamentNumberFields::quantityInput(
                        TextInput::make('replenish_target_quantity')
                            ->label(__('dberp.fields.replenish_target_quantity'))
                            ->default(0),
                        withHelperText: false,
                        minValue: 0.0,
                    ),
                    TextInput::make('expiry_warning_days')
                        ->label(__('dberp.fields.expiry_warning_days'))
                        ->numeric()
                        ->default(0)
                        ->helperText((string) __('dberp.hints.inventory_rule_expiry_warning_follows_product')),
                    Toggle::make('warning_enabled')
                        ->label(__('dberp.fields.warning_enabled'))
                        ->default(true)
                        ->helperText((string) __('dberp.hints.inventory_rule_warning_enabled')),
                    Toggle::make('replenishment_enabled')
                        ->label(__('dberp.fields.replenishment_enabled'))
                        ->default(true)
                        ->helperText((string) __('dberp.hints.inventory_rule_replenishment_enabled')),
                    Toggle::make('is_enabled')
                        ->label(__('dberp.fields.is_enabled'))
                        ->default(true),
                    Select::make('inventory_issue_policy')
                        ->label(__('dberp.fields.inventory_issue_policy'))
                        ->options(__('dberp.options.inventory_issue_policy'))
                        ->required()
                        ->helperText((string) __('dberp.hints.inventory_rule_issue_policy_follows_product')),
                    TextInput::make('sort_order')
                        ->label(__('dberp.fields.sort_order'))
                        ->numeric()
                        ->default(0)
                        ->required(),
                    Textarea::make('remark')
                        ->label(__('dberp.fields.remark'))
                        ->rows(3)
                        ->columnSpanFull(),
                ])
                ->columns(3),
        ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('sort_order', 'asc')
            ->columns([
                TextColumn::make('product.code')->label(__('dberp.fields.product_code'))->searchable(),
                TextColumn::make('product.name')->label(__('dberp.fields.product_name'))->searchable(),
                TextColumn::make('warehouse.name')->label(__('dberp.fields.warehouse')),
                TextColumn::make('available_quantity_snapshot')
                    ->label(__('dberp.fields.available_quantity'))
                    ->state(fn (DberpInventoryRule $record): string => app(InventoryRuleEvaluatorService::class)->metrics($record)['available_quantity']),
                TextColumn::make('safety_stock')->label(__('dberp.fields.safety_stock'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('reorder_point')->label(__('dberp.fields.reorder_point'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('replenish_target_quantity')->label(__('dberp.fields.replenish_target_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                ToggleColumn::make('warning_enabled')
                    ->label(__('dberp.fields.warning_enabled')),
                ToggleColumn::make('replenishment_enabled')
                    ->label(__('dberp.fields.replenishment_enabled')),
                ToggleColumn::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
            ])
            ->filters([
                SelectFilter::make('warehouse_id')->label(__('dberp.fields.warehouse'))->relationship('warehouse', 'name'),
                DberpProductSkuSelectOptions::configureProductRelationshipTableFilter(
                    SelectFilter::make('product_id')->label(__('dberp.fields.product')),
                ),
                TernaryFilter::make('warning_enabled')->label(__('dberp.fields.warning_enabled')),
                TernaryFilter::make('replenishment_enabled')->label(__('dberp.fields.replenishment_enabled')),
                TernaryFilter::make('is_enabled')->label(__('dberp.fields.is_enabled')),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make()
                    ->visible(fn (DberpInventoryRule $record): bool => static::canDelete($record))
                    ->authorize(fn (DberpInventoryRule $record): bool => static::canDelete($record)),
            ]);
    }

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

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

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

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

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

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

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