<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpOtherStockInOrders;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Business\Inventory\InventoryRuleService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentCreateSaveFirstGuidance;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpOtherStockInOrders\Pages\CreateDberpOtherStockInOrder;
use App\Filament\Resources\DberpOtherStockInOrders\Pages\EditDberpOtherStockInOrder;
use App\Filament\Resources\DberpOtherStockInOrders\Pages\ListDberpOtherStockInOrders;
use App\Filament\Resources\DberpOtherStockInOrders\RelationManagers\ItemsRelationManager;
use App\Models\DberpOtherStockInOrder;
use App\Models\DberpWarehouse;
use App\Services\DberpPermissionService;
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\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpOtherStockInOrderResource extends Resource implements DberpFilamentCreateSaveFirstGuidance, DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 40;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpOtherStockInOrder
            && $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.stock_in_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpOtherStockInOrder $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())
                            ->default(fn (): ?int => app(InventoryRuleService::class)->defaultWarehouseId())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpOtherStockInOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        TextInput::make('reason')
                            ->label(__('dberp.fields.reason'))
                            ->required()
                            ->maxLength(255)
                            ->disabled(fn (?DberpOtherStockInOrder $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 (?DberpOtherStockInOrder $record): bool => $record !== null && $record->status !== InventoryDocumentStatus::Draft->value),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpOtherStockInOrder $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.stock_in_code'))
                    ->searchable(),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse'))
                    ->searchable(),
                TextColumn::make('reason')
                    ->label(__('dberp.fields.reason'))
                    ->searchable(),
                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'),
            ]);
    }

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

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

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

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

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpOtherStockInOrders::route('/'),
            'create' => CreateDberpOtherStockInOrder::route('/create'),
            'edit' => EditDberpOtherStockInOrder::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.other_stock_in.label');
    }

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