<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpStocktakeOrders;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\Enums\StocktakeScopeType;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpStocktakeOrders\Pages\CreateDberpStocktakeOrder;
use App\Filament\Resources\DberpStocktakeOrders\Pages\EditDberpStocktakeOrder;
use App\Filament\Resources\DberpStocktakeOrders\Pages\ListDberpStocktakeOrders;
use App\Filament\Resources\DberpStocktakeOrders\RelationManagers\ItemsRelationManager;
use App\Models\DberpEmployee;
use App\Models\DberpProductCategory;
use App\Models\DberpStocktakeOrder;
use App\Models\DberpWarehouse;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpProductSkuSelectOptions;
use BackedEnum;
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\Components\Utilities\Get;
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 DberpStocktakeOrderResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 70;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpStocktakeOrder
            && $record->status === InventoryDocumentStatus::Draft->value;
    }

    public static function createSaveFirstGuidanceTranslationKey(): ?string
    {
        return 'dberp.messages.save_document_first_then_manage_lines';
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.inventory_document'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.stocktake_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('warehouse_id')
                            ->label(__('dberp.fields.warehouse'))
                            ->options(fn (): array => DberpWarehouse::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('scope_type')
                            ->label(__('dberp.fields.scope_type'))
                            ->options(__('dberp.options.stocktake_scope_type'))
                            ->default(StocktakeScopeType::All->value)
                            ->required()
                            ->live()
                            ->helperText(__('dberp.hints.stocktake_scope'))
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('scope_category_id')
                            ->label(__('dberp.fields.scope_category'))
                            ->options(fn (): array => DberpProductCategory::query()
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->visible(fn (Get $get): bool => $get('scope_type') === StocktakeScopeType::Category->value)
                            ->required(fn (Get $get): bool => $get('scope_type') === StocktakeScopeType::Category->value)
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('scope_product_id')
                            ->label(__('dberp.fields.scope_product'))
                            ->options(fn (): array => DberpFilamentMasterDataSelectOptions::products(
                                enabledOnly: true,
                                scope: DberpProductSkuSelectOptions::PRODUCT_SCOPE_INVENTORY,
                            ))
                            ->searchable()
                            ->preload()
                            ->visible(fn (Get $get): bool => $get('scope_type') === StocktakeScopeType::Product->value)
                            ->required(fn (Get $get): bool => $get('scope_type') === StocktakeScopeType::Product->value)
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Select::make('stocktake_employee_id')
                            ->label(__('dberp.fields.stocktake_employee'))
                            ->options(fn (): array => DberpEmployee::selectOptionsForFilament(
                                fn (Builder $q) => $q->where('is_enabled', true),
                            ))
                            ->searchable()
                            ->preload()
                            ->nullable()
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        DateTimePicker::make('business_time')
                            ->label(__('dberp.fields.business_time'))
                            ->default(now())
                            ->required()
                            ->seconds(false)
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpStocktakeOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.stocktake_code'))
                    ->searchable(),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse'))
                    ->searchable(),
                TextColumn::make('scope_type')
                    ->label(__('dberp.fields.scope_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.stocktake_scope_type.'.(string) $state)),
                TextColumn::make('stocktakeEmployee.name')
                    ->label(__('dberp.fields.stocktake_employee')),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryDocumentStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('business_time')
                    ->label(__('dberp.fields.business_time'))
                    ->dateTime(),
                TextColumn::make('effective_at')
                    ->label(__('dberp.fields.effective_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('voided_at')
                    ->label(__('dberp.fields.voided_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(__('dberp.options.inventory_doc_status')),
                SelectFilter::make('warehouse_id')
                    ->label(__('dberp.fields.warehouse'))
                    ->relationship('warehouse', 'name'),
                SelectFilter::make('scope_type')
                    ->label(__('dberp.fields.scope_type'))
                    ->options(__('dberp.options.stocktake_scope_type')),
            ]);
    }

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

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

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

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

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

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

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

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

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