<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpInventoryBatches;

use App\Business\Inventory\Enums\InventoryExpiryStatus;
use App\Business\Inventory\InventoryBatchService;
use App\Business\Inventory\InventoryExpiryService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpInventoryBatches\Pages\CreateDberpInventoryBatch;
use App\Filament\Resources\DberpInventoryBatches\Pages\EditDberpInventoryBatch;
use App\Filament\Resources\DberpInventoryBatches\Pages\ListDberpInventoryBatches;
use App\Filament\Resources\DberpInventoryBatches\Pages\ViewDberpInventoryBatch;
use App\Filament\Resources\DberpInventoryBatches\RelationManagers\InventoryBatchMovementsRelationManager;
use App\Filament\Resources\DberpInventoryBatches\RelationManagers\InventoryBatchSerialNumbersRelationManager;
use App\Models\DberpInventoryBatch;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use App\Support\DberpSourceSystemLabels;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DatePicker;
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\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\Builder;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpInventoryBatchResource extends Resource implements DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'batch_no';

    protected static ?int $navigationSort = 110;

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

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

    /**
     * @return array<class-string>
     */
    public static function getRelations(): array
    {
        return [
            InventoryBatchMovementsRelationManager::class,
            InventoryBatchSerialNumbersRelationManager::class,
        ];
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.inventory_batch'))
                ->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(),
                    TextInput::make('batch_no')
                        ->label(__('dberp.fields.batch_no'))
                        ->required()
                        ->maxLength(64),
                    Select::make('status')
                        ->label(__('dberp.fields.batch_status'))
                        ->options(__('dberp.options.inventory_batch_status'))
                        ->required(),
                    TextInput::make('source_system')
                        ->label(__('dberp.fields.source_system'))
                        ->default('dberp')
                        ->maxLength(32),
                    TextInput::make('source_document_type')
                        ->label(__('dberp.fields.source_type'))
                        ->maxLength(120),
                    TextInput::make('source_document_no')
                        ->label(__('dberp.fields.source_document_no'))
                        ->maxLength(64),
                    TextInput::make('external_reference_id')
                        ->label(__('dberp.fields.external_reference_id'))
                        ->maxLength(128),
                    DatePicker::make('production_date')
                        ->label(__('dberp.fields.production_date')),
                    DatePicker::make('expiry_date')
                        ->label(__('dberp.fields.expiry_date')),
                    TextInput::make('shelf_life_days')
                        ->label(__('dberp.fields.shelf_life_days'))
                        ->numeric()
                        ->default(0),
                    TextInput::make('realtime_quantity')
                        ->label(__('dberp.fields.realtime_quantity'))
                        ->numeric()
                        ->default(0),
                    TextInput::make('available_quantity')
                        ->label(__('dberp.fields.available_quantity'))
                        ->numeric()
                        ->default(0),
                    TextInput::make('locked_quantity')
                        ->label(__('dberp.fields.locked_quantity'))
                        ->numeric()
                        ->default(0),
                    TextInput::make('sort_order')
                        ->label(__('dberp.fields.sort_order'))
                        ->numeric()
                        ->default(0)
                        ->required(),
                    Toggle::make('is_enabled')
                        ->label(__('dberp.fields.is_enabled'))
                        ->default(true),
                    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('batch_no')->label(__('dberp.fields.batch_no'))->searchable(),
                TextColumn::make('status')
                    ->label(__('dberp.fields.batch_status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.inventory_batch_status')[$state] ?? (string) $state),
                TextColumn::make('expiry_status')
                    ->label(__('dberp.fields.expiry_status'))
                    ->badge()
                    ->state(fn (DberpInventoryBatch $record): string => app(InventoryBatchService::class)->expiryStatus($record)->value)
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.inventory_expiry_status')[$state] ?? (string) $state),
                TextColumn::make('available_quantity')->label(__('dberp.fields.available_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('locked_quantity')->label(__('dberp.fields.locked_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('expiry_date')->label(__('dberp.fields.expiry_date'))->date(),
                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')),
                ),
                SelectFilter::make('status')->label(__('dberp.fields.batch_status'))->options(__('dberp.options.inventory_batch_status')),
                SelectFilter::make('expiry_status')
                    ->label(__('dberp.fields.expiry_status'))
                    ->options(InventoryExpiryStatus::options())
                    ->query(function (Builder $query, array $data): void {
                        $value = $data['value'] ?? null;

                        if ($value === null || $value === '') {
                            return;
                        }

                        app(InventoryExpiryService::class)->constrainBatchQueryToExpiryStatus($query, (string) $value);
                    }),
                TernaryFilter::make('is_enabled')->label(__('dberp.fields.is_enabled')),
            ])
            ->recordActions([
                ViewAction::make(),
                EditAction::make(),
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.inventory_batch'))
                ->schema([
                    TextEntry::make('product.code')->label(__('dberp.fields.product_code')),
                    TextEntry::make('product.name')->label(__('dberp.fields.product_name')),
                    TextEntry::make('warehouse.name')->label(__('dberp.fields.warehouse')),
                    TextEntry::make('batch_no')->label(__('dberp.fields.batch_no')),
                    TextEntry::make('status')
                        ->label(__('dberp.fields.batch_status'))
                        ->badge()
                        ->formatStateUsing(fn (?string $state): string => __('dberp.options.inventory_batch_status')[$state] ?? (string) $state),
                    TextEntry::make('expiry_status')
                        ->label(__('dberp.fields.expiry_status'))
                        ->badge()
                        ->state(fn (DberpInventoryBatch $record): string => app(InventoryBatchService::class)->expiryStatus($record)->value)
                        ->formatStateUsing(fn (?string $state): string => __('dberp.options.inventory_expiry_status')[$state] ?? (string) $state),
                    IconEntry::make('is_enabled')->label(__('dberp.fields.is_enabled'))->boolean(),
                    TextEntry::make('production_date')->label(__('dberp.fields.production_date'))->date(),
                    TextEntry::make('expiry_date')->label(__('dberp.fields.expiry_date'))->date(),
                    TextEntry::make('shelf_life_days')->label(__('dberp.fields.shelf_life_days')),
                    TextEntry::make('sort_order')->label(__('dberp.fields.sort_order')),
                    TextEntry::make('realtime_quantity')->label(__('dberp.fields.realtime_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                    TextEntry::make('available_quantity')->label(__('dberp.fields.available_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                    TextEntry::make('locked_quantity')->label(__('dberp.fields.locked_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                    TextEntry::make('source_system')
                        ->label(__('dberp.fields.source_system'))
                        ->formatStateUsing(fn (?string $state): string => DberpSourceSystemLabels::label($state)),
                    TextEntry::make('source_document_type')->label(__('dberp.fields.source_type')),
                    TextEntry::make('source_document_no')->label(__('dberp.fields.source_document_no')),
                    TextEntry::make('external_reference_id')->label(__('dberp.fields.external_reference_id')),
                    TextEntry::make('remark')->label(__('dberp.fields.remark'))->columnSpanFull(),
                ])
                ->columns(3),
        ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpInventoryBatches::route('/'),
            'create' => CreateDberpInventoryBatch::route('/create'),
            'view' => ViewDberpInventoryBatch::route('/{record}'),
            'edit' => EditDberpInventoryBatch::route('/{record}/edit'),
        ];
    }

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_INVENTORY_BATCH,
            DberpPermissionService::MANAGE_INVENTORY_BATCH,
            DberpPermissionService::DISABLE_INVENTORY_BATCH,
        ]);
    }

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

    public static function canEdit(Model $record): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::MANAGE_INVENTORY_BATCH,
            DberpPermissionService::DISABLE_INVENTORY_BATCH,
        ]);
    }

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

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