<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpProducts;

use App\Business\Product\ProductCategoryTreeService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpProducts\Concerns\ProvidesDberpProductBusinessOverviewSections;
use App\Filament\Resources\DberpProducts\Pages\CreateDberpProduct;
use App\Filament\Resources\DberpProducts\Pages\EditDberpProduct;
use App\Filament\Resources\DberpProducts\Pages\ListDberpProducts;
use App\Filament\Resources\DberpProducts\Pages\ViewDberpProduct;
use App\Filament\Resources\DberpProducts\RelationManagers\ProductSkusRelationManager;
use App\Filament\Resources\DberpProducts\RelationManagers\ProductSpecGroupsRelationManager;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpProduct;
use App\Models\DberpProductBrand;
use App\Models\DberpUnit;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductAuxiliaryUnitPreview;
use App\Support\PluginIntegration\BarcodeLabelFilamentBridge;
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\Resource;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Components\Grid;
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\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Contracts\HasTable;
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 DberpProductResource extends Resource
{
    use InteractsWithDberpPermissions;
    use ProvidesDberpProductBusinessOverviewSections;

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

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 20;

    protected static bool $isGloballySearchable = true;

    protected static ?int $globalSearchSort = 10;

    protected static int $globalSearchResultsLimit = 30;

    /**
     * @return array<int, string>
     */
    public static function getGloballySearchableAttributes(): array
    {
        return ['code', 'name', 'spec_model', 'barcode'];
    }

    public static function getGlobalSearchEloquentQuery(): Builder
    {
        return static::getModel()::query();
    }

    /**
     * @return array<string, string>
     */
    public static function getGlobalSearchResultDetails(Model $record): array
    {
        if (! $record instanceof DberpProduct) {
            return [];
        }

        $details = [
            (string) __('dberp.global_search.detail_code') => (string) $record->code,
        ];

        if (filled($record->spec_model)) {
            $details[(string) __('dberp.global_search.detail_spec')] = (string) $record->spec_model;
        }

        if (filled($record->barcode)) {
            $details[(string) __('dberp.global_search.detail_barcode')] = (string) $record->barcode;
        }

        return array_filter($details, static fn (string $v): bool => $v !== '');
    }

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

    public static function getRelations(): array
    {
        return [
            ProductSpecGroupsRelationManager::class,
            ProductSkusRelationManager::class,
        ];
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->columns(3)
            ->components([
                ...static::productBusinessOverviewSections(),
                // ── 左侧主区（跨 2 列）──────────────────────────────────────
                Section::make(__('dberp.sections.product_archive'))
                    ->columnSpan(2)
                    ->columns(2)
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.product_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code')),
                        TextInput::make('name')
                            ->label(__('dberp.fields.product_name'))
                            ->required()
                            ->maxLength(160),
                        Select::make('category_id')
                            ->label(__('dberp.fields.category'))
                            ->options(fn (): array => app(ProductCategoryTreeService::class)->options())
                            ->searchable()
                            ->preload()
                            ->nullable(),
                        Select::make('brand_id')
                            ->label(__('dberp.fields.product_brand_selector'))
                            ->placeholder(__('dberp.placeholders.product_brand'))
                            ->options(function (Select $component): array {
                                $record = $component->getRecord();
                                $preserveId = null;
                                if ($record instanceof DberpProduct && $record->exists && $record->brand_id !== null) {
                                    $preserveId = (int) $record->brand_id;
                                }

                                return DberpProductBrand::optionsForProductForm($preserveId);
                            })
                            ->preload()
                            ->searchable(fn (): bool => DberpProductBrand::query()->count() > 25)
                            ->native(false)
                            ->nullable()
                            ->helperText(__('dberp.hints.product_brand_selector')),
                        TextInput::make('barcode')
                            ->label(__('dberp.fields.barcode'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true),
                        TextInput::make('mnemonic_code')
                            ->label(__('dberp.fields.mnemonic_code'))
                            ->maxLength(64),
                        TextInput::make('spec_model')
                            ->label(__('dberp.fields.spec_model'))
                            ->maxLength(160)
                            ->helperText(__('dberp.hints.product_spec_strategy'))
                            ->columnSpanFull(),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(2)
                            ->columnSpanFull(),
                    ]),

                // ── 右侧辅栏（1 列）──────────────────────────────────────────
                Grid::make(1)
                    ->columnSpan(1)
                    ->schema([
                        Section::make(__('dberp.sections.product_business'))
                            ->columns(1)
                            ->schema([
                                DberpFilamentNumberFields::moneyInput(
                                    TextInput::make('cost_price')
                                        ->label(__('dberp.fields.cost_price'))
                                        ->default(0),
                                    withHelperText: false,
                                    minValue: 0.0,
                                ),
                                DberpFilamentNumberFields::moneyInput(
                                    TextInput::make('sales_price')
                                        ->label(__('dberp.fields.sales_price'))
                                        ->default(0),
                                    withHelperText: false,
                                    minValue: 0.0,
                                ),
                                TextInput::make('sort_order')
                                    ->label(__('dberp.fields.sort_order'))
                                    ->numeric()
                                    ->default(0)
                                    ->required(),
                                Fieldset::make(__('dberp.sections.product_business_flags'))
                                    ->columns(1)
                                    ->schema([
                                        Toggle::make('can_purchase')
                                            ->label(__('dberp.fields.can_purchase'))
                                            ->default(true),
                                        Toggle::make('can_sale')
                                            ->label(__('dberp.fields.can_sale'))
                                            ->default(true),
                                        Toggle::make('manages_inventory')
                                            ->label(__('dberp.fields.manages_inventory'))
                                            ->default(true)
                                            ->live()
                                            ->afterStateUpdated(function (Set $set, ?bool $state): void {
                                                if ($state) {
                                                    return;
                                                }

                                                $set('manages_batch', false);
                                                $set('manages_serial_number', false);
                                                $set('manages_expiry', false);
                                            }),
                                        Toggle::make('manages_batch')
                                            ->label(__('dberp.fields.manages_batch'))
                                            ->default(false)
                                            ->visible(fn (Get $get): bool => (bool) $get('manages_inventory')),
                                        Toggle::make('manages_serial_number')
                                            ->label(__('dberp.fields.manages_serial_number'))
                                            ->default(false)
                                            ->visible(fn (Get $get): bool => (bool) $get('manages_inventory')),
                                        Toggle::make('manages_expiry')
                                            ->label(__('dberp.fields.manages_expiry'))
                                            ->default(false)
                                            ->visible(fn (Get $get): bool => (bool) $get('manages_inventory')),
                                        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'))
                                    ->default('fifo')
                                    ->required()
                                    ->visible(fn (Get $get): bool => (bool) $get('manages_inventory') && (bool) $get('manages_batch')),
                                TextInput::make('expiry_warning_days')
                                    ->label(__('dberp.fields.expiry_warning_days'))
                                    ->numeric()
                                    ->default(0)
                                    ->visible(fn (Get $get): bool => (bool) $get('manages_inventory') && (bool) $get('manages_expiry')),
                            ]),
                    ]),

                // ── 计量与单位配置（全宽）────────────────────────────────────
                Section::make(__('dberp.sections.product_unit_configuration'))
                    ->description(__('dberp.hints.product_unit_configuration_intro'))
                    ->columnSpanFull()
                    ->columns(4)
                    ->schema([
                        Select::make('unit_id')
                            ->label(__('dberp.fields.product_base_unit'))
                            ->options(fn (): array => DberpUnit::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable(fn (): bool => DberpUnit::query()->where('is_enabled', true)->count() > 20)
                            ->preload()
                            ->required()
                            ->live()
                            ->columnSpan(1),
                        Toggle::make('is_auxiliary_unit_enabled')
                            ->label(__('dberp.fields.is_auxiliary_unit_enabled'))
                            ->default(false)
                            ->live()
                            ->columnSpan(1),
                        Select::make('auxiliary_unit_id')
                            ->label(__('dberp.fields.auxiliary_unit'))
                            ->options(function (Get $get): array {
                                $baseId = (int) ($get('unit_id') ?? 0);

                                $query = DberpUnit::query()
                                    ->where('is_enabled', true)
                                    ->orderBy('sort_order')
                                    ->orderBy('id');

                                if ($baseId > 0) {
                                    $query->where('id', '!=', $baseId);
                                }

                                return $query->pluck('name', 'id')->all();
                            })
                            ->searchable(fn (): bool => DberpUnit::query()->where('is_enabled', true)->count() > 20)
                            ->preload()
                            ->nullable()
                            ->live()
                            ->visible(fn (Get $get): bool => (bool) $get('is_auxiliary_unit_enabled'))
                            ->required(fn (Get $get): bool => (bool) $get('is_auxiliary_unit_enabled'))
                            ->columnSpan(1),
                        DberpFilamentNumberFields::productAuxiliaryConversionQuantityInput(
                            TextInput::make('auxiliary_unit_quantity')
                                ->label(__('dberp.fields.auxiliary_unit_quantity'))
                                ->nullable()
                                ->visible(fn (Get $get): bool => (bool) $get('is_auxiliary_unit_enabled'))
                                ->required(fn (Get $get): bool => (bool) $get('is_auxiliary_unit_enabled'))
                                ->columnSpan(1),
                        ),
                        DberpFilamentNumberFields::productAuxiliaryConversionQuantityInput(
                            TextInput::make('base_unit_quantity')
                                ->label(__('dberp.fields.base_unit_quantity'))
                                ->nullable()
                                ->visible(fn (Get $get): bool => (bool) $get('is_auxiliary_unit_enabled'))
                                ->required(fn (Get $get): bool => (bool) $get('is_auxiliary_unit_enabled'))
                                ->columnSpan(1),
                        ),
                        Placeholder::make('_product_auxiliary_conversion_preview')
                            ->label(__('dberp.fields.product_auxiliary_conversion_preview'))
                            ->content(function (Get $get): string {
                                $line = DberpProductAuxiliaryUnitPreview::fromFormGet($get);

                                return $line !== ''
                                    ? $line
                                    : (string) __('dberp.hints.product_auxiliary_preview_placeholder');
                            })
                            ->visible(fn (Get $get): bool => (bool) $get('is_auxiliary_unit_enabled'))
                            ->columnSpan(2),
                        Placeholder::make('_product_auxiliary_save_guidance')
                            ->hiddenLabel()
                            ->content(fn (): string => (string) __('dberp.messages.save_product_first_then_manage_auxiliary_units'))
                            ->visible(fn (Get $get, ?Model $record): bool => self::shouldShowProductAuxiliarySaveGuidance($get, $record))
                            ->columnSpanFull(),
                    ]),

                // ── 商品规格（全宽）──────────────────────────────────────────
                Section::make(__('dberp.sections.product_spec'))
                    ->columnSpanFull()
                    ->columns(1)
                    ->schema([
                        Toggle::make('spec_enabled')
                            ->label(__('dberp.fields.spec_enabled'))
                            ->helperText(__('dberp.hints.product_spec_enabled'))
                            ->default(false)
                            ->live(),
                        Placeholder::make('_product_spec_save_guidance')
                            ->hiddenLabel()
                            ->content(fn (): string => (string) __('dberp.messages.save_product_first_then_manage_specs'))
                            ->visible(fn (Get $get, ?Model $record): bool => self::shouldShowProductSpecSaveGuidance($get, $record))
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort(
                function (Builder $query, string $direction, HasTable $livewire): Builder {
                    $dir = $direction === 'desc' ? 'desc' : 'asc';
                    $primaryColumn = $livewire->getTableSortColumn();

                    if ($primaryColumn === null) {
                        return $query
                            ->orderBy($query->qualifyColumn('sort_order'), $dir)
                            ->orderBy($query->qualifyColumn('id'), 'desc');
                    }

                    if ($primaryColumn === 'sort_order') {
                        return $query->orderBy($query->qualifyColumn('id'), 'desc');
                    }

                    return $query
                        ->orderBy($query->qualifyColumn('sort_order'), $dir)
                        ->orderBy($query->qualifyColumn('id'), 'desc');
                },
                'asc',
            )
            ->defaultKeySort(false)
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.product_code'))
                    ->searchable(),
                TextColumn::make('name')
                    ->label(__('dberp.fields.product_name'))
                    ->searchable(),
                TextColumn::make('category.name')
                    ->label(__('dberp.fields.category')),
                TextColumn::make('brand.name')
                    ->label(__('dberp.fields.product_brand_selector'))
                    ->formatStateUsing(fn (mixed $state, Model $record): string => $record instanceof DberpProduct
                        ? $record->getBusinessBrandDisplay()
                        : '—'),
                TextColumn::make('unit.name')
                    ->label(__('dberp.fields.product_base_unit')),
                IconColumn::make('is_auxiliary_unit_enabled')
                    ->label(__('dberp.fields.is_auxiliary_unit_enabled'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('auxiliary_conversion_preview')
                    ->label(__('dberp.fields.product_auxiliary_conversion_preview'))
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->wrap()
                    ->state(function (DberpProduct $record): string {
                        $line = DberpProductAuxiliaryUnitPreview::fromProduct($record);

                        return $line !== ''
                            ? $line
                            : (string) __('dberp.messages.product_auxiliary_not_enabled');
                    }),
                IconColumn::make('spec_enabled')
                    ->label(__('dberp.fields.spec_enabled'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('sales_price')
                    ->label(__('dberp.fields.sales_price'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::price($state)),
                ToggleColumn::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                IconColumn::make('can_purchase')
                    ->label(__('dberp.fields.can_purchase'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                IconColumn::make('can_sale')
                    ->label(__('dberp.fields.can_sale'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                IconColumn::make('manages_inventory')
                    ->label(__('dberp.fields.manages_inventory'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                IconColumn::make('manages_batch')
                    ->label(__('dberp.fields.manages_batch'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                IconColumn::make('manages_serial_number')
                    ->label(__('dberp.fields.manages_serial_number'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                IconColumn::make('manages_expiry')
                    ->label(__('dberp.fields.manages_expiry'))
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('sort_order')
                    ->label(__('dberp.fields.sort_order'))
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('brand_id')
                    ->label(__('dberp.fields.product_brand_selector'))
                    ->options(fn (): array => DberpProductBrand::query()
                        ->orderBy('sort_order')
                        ->orderBy('id')
                        ->get()
                        ->mapWithKeys(fn (DberpProductBrand $b): array => [
                            (string) $b->getKey() => DberpProductBrand::formatOptionLabel($b),
                        ])
                        ->all())
                    ->searchable(fn (): bool => DberpProductBrand::query()->count() > 20)
                    ->preload(),
                TernaryFilter::make('is_enabled')
                    ->label(__('dberp.fields.is_enabled')),
                TernaryFilter::make('can_sale')
                    ->label(__('dberp.fields.can_sale')),
                TernaryFilter::make('can_purchase')
                    ->label(__('dberp.fields.can_purchase')),
                TernaryFilter::make('manages_batch')
                    ->label(__('dberp.fields.manages_batch')),
                TernaryFilter::make('manages_serial_number')
                    ->label(__('dberp.fields.manages_serial_number')),
                TernaryFilter::make('manages_expiry')
                    ->label(__('dberp.fields.manages_expiry')),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->toolbarActions([
                ...BarcodeLabelFilamentBridge::productTableToolbarActions(),
            ]);
    }

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

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

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

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

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

    public static function infolist(Schema $schema): Schema
    {
        return $schema->components([
            ...static::productBusinessOverviewSections(),
            Section::make(__('dberp.sections.product_archive'))
                ->schema([
                    TextEntry::make('code')->label(__('dberp.fields.product_code')),
                    TextEntry::make('name')->label(__('dberp.fields.product_name')),
                    TextEntry::make('category.name')->label(__('dberp.fields.category')),
                    TextEntry::make('brand_display')
                        ->label(__('dberp.fields.product_brand_selector'))
                        ->state(fn (DberpProduct $record): string => $record->getBusinessBrandDisplay()),
                    TextEntry::make('barcode')->label(__('dberp.fields.barcode')),
                    TextEntry::make('mnemonic_code')->label(__('dberp.fields.mnemonic_code')),
                    TextEntry::make('spec_model')
                        ->label(__('dberp.fields.spec_model'))
                        ->columnSpanFull(),
                ])
                ->columns(2),
            Section::make(__('dberp.sections.product_unit_configuration'))
                ->schema([
                    TextEntry::make('unit.name')->label(__('dberp.fields.product_base_unit')),
                    IconEntry::make('is_auxiliary_unit_enabled')
                        ->label(__('dberp.fields.is_auxiliary_unit_enabled'))
                        ->boolean(),
                    TextEntry::make('auxiliaryUnit.name')
                        ->label(__('dberp.fields.auxiliary_unit'))
                        ->visible(fn (DberpProduct $record): bool => (bool) $record->is_auxiliary_unit_enabled),
                    TextEntry::make('auxiliary_unit_quantity')
                        ->label(__('dberp.fields.auxiliary_unit_quantity'))
                        ->formatStateUsing(fn ($state): string => $state === null || $state === '' ? '—' : DberpNumberFormatter::quantity($state))
                        ->visible(fn (DberpProduct $record): bool => (bool) $record->is_auxiliary_unit_enabled),
                    TextEntry::make('base_unit_quantity')
                        ->label(__('dberp.fields.base_unit_quantity'))
                        ->formatStateUsing(fn ($state): string => $state === null || $state === '' ? '—' : DberpNumberFormatter::quantity($state))
                        ->visible(fn (DberpProduct $record): bool => (bool) $record->is_auxiliary_unit_enabled),
                    TextEntry::make('conversion_preview_detail')
                        ->label(__('dberp.fields.product_auxiliary_conversion_preview'))
                        ->state(function (DberpProduct $record): string {
                            if (! (bool) $record->is_auxiliary_unit_enabled) {
                                return (string) __('dberp.messages.product_auxiliary_not_enabled');
                            }

                            $line = DberpProductAuxiliaryUnitPreview::fromProduct($record);

                            return $line !== ''
                                ? $line
                                : (string) __('dberp.hints.product_auxiliary_preview_placeholder');
                        }),
                ])
                ->columns(2),
            Section::make(__('dberp.sections.product_business'))
                ->schema([
                    TextEntry::make('cost_price')->label(__('dberp.fields.cost_price'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::costPrice($state)),
                    TextEntry::make('sales_price')->label(__('dberp.fields.sales_price'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::price($state)),
                    TextEntry::make('sort_order')->label(__('dberp.fields.sort_order')),
                    IconEntry::make('can_purchase')->label(__('dberp.fields.can_purchase'))->boolean(),
                    IconEntry::make('can_sale')->label(__('dberp.fields.can_sale'))->boolean(),
                    IconEntry::make('manages_inventory')->label(__('dberp.fields.manages_inventory'))->boolean(),
                    IconEntry::make('manages_batch')
                        ->label(__('dberp.fields.manages_batch'))
                        ->boolean()
                        ->visible(fn (DberpProduct $record): bool => $record->manages_inventory),
                    IconEntry::make('manages_serial_number')
                        ->label(__('dberp.fields.manages_serial_number'))
                        ->boolean()
                        ->visible(fn (DberpProduct $record): bool => $record->manages_inventory),
                    IconEntry::make('manages_expiry')
                        ->label(__('dberp.fields.manages_expiry'))
                        ->boolean()
                        ->visible(fn (DberpProduct $record): bool => $record->manages_inventory),
                    TextEntry::make('inventory_issue_policy')
                        ->label(__('dberp.fields.inventory_issue_policy'))
                        ->visible(fn (DberpProduct $record): bool => $record->manages_inventory && $record->manages_batch)
                        ->formatStateUsing(function (?string $state): string {
                            if ($state === null || $state === '') {
                                return '—';
                            }

                            $options = __('dberp.options.inventory_issue_policy');

                            return is_array($options) && array_key_exists($state, $options)
                                ? (string) $options[$state]
                                : $state;
                        }),
                    TextEntry::make('expiry_warning_days')
                        ->label(__('dberp.fields.expiry_warning_days'))
                        ->visible(fn (DberpProduct $record): bool => $record->manages_inventory && $record->manages_expiry),
                    IconEntry::make('is_enabled')->label(__('dberp.fields.is_enabled'))->boolean(),
                    TextEntry::make('remark')->label(__('dberp.fields.remark'))->columnSpanFull(),
                ])
                ->columns(3),
            Section::make(__('dberp.sections.product_spec'))
                ->schema([
                    IconEntry::make('spec_enabled')->label(__('dberp.fields.spec_enabled'))->boolean(),
                ])
                ->columns(1),
        ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpProducts::route('/'),
            'create' => CreateDberpProduct::route('/create'),
            'view' => ViewDberpProduct::route('/{record}'),
            'edit' => EditDberpProduct::route('/{record}/edit'),
        ];
    }

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

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

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

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

    private static function shouldShowProductSpecSaveGuidance(Get $get, ?Model $record): bool
    {
        if (! (bool) $get('spec_enabled')) {
            return false;
        }

        if (! $record instanceof DberpProduct || ! $record->exists) {
            return true;
        }

        return ! (bool) $record->spec_enabled;
    }

    private static function shouldShowProductAuxiliarySaveGuidance(Get $get, ?Model $record): bool
    {
        if (! (bool) $get('is_auxiliary_unit_enabled')) {
            return false;
        }

        if (! $record instanceof DberpProduct || ! $record->exists) {
            return true;
        }

        return ! (bool) $record->is_auxiliary_unit_enabled;
    }
}
