<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpInventoryReplenishmentSuggestions;

use App\Business\Inventory\Enums\InventoryReplenishmentSuggestionStatus;
use App\Business\Purchase\PurchaseRequestGenerationService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpInventoryReplenishmentSuggestions\Pages\EditDberpInventoryReplenishmentSuggestion;
use App\Filament\Resources\DberpInventoryReplenishmentSuggestions\Pages\ListDberpInventoryReplenishmentSuggestions;
use App\Filament\Resources\DberpPurchaseRequests\DberpPurchaseRequestResource;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Filament\Support\DberpFilamentRecordTitles;
use App\Models\DberpInventoryReplenishmentSuggestion;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
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 DberpInventoryReplenishmentSuggestionResource extends Resource
{
    use InteractsWithDberpPermissions;

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

    protected static ?int $navigationSort = 100;

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

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

        return DberpFilamentRecordTitles::inventoryReplenishmentSuggestion($record);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make(__('dberp.sections.inventory_replenishment_suggestion'))
                ->schema([
                    DberpProductSkuSelectOptions::configureInventoryProductRelationshipSelect(
                        Select::make('product_id')
                            ->label(__('dberp.fields.product')),
                    )->disabled(),
                    Select::make('warehouse_id')
                        ->label(__('dberp.fields.warehouse'))
                        ->relationship('warehouse', 'name')
                        ->searchable()
                        ->preload()
                        ->disabled(),
                    TextInput::make('system_suggested_quantity')
                        ->label(__('dberp.fields.system_suggested_quantity'))
                        ->numeric()
                        ->disabled(),
                    DberpFilamentNumberFields::quantityInput(
                        TextInput::make('adjusted_quantity')
                            ->label(__('dberp.fields.adjusted_quantity'))
                            ->default(0),
                        withHelperText: false,
                        minValue: 0.0,
                    ),
                    TextInput::make('trigger_reason')
                        ->label(__('dberp.fields.trigger_reason'))
                        ->disabled(),
                    Select::make('status')
                        ->label(__('dberp.fields.replenishment_suggestion_status'))
                        ->options(__('dberp.options.inventory_replenishment_suggestion_status'))
                        ->required(),
                    DateTimePicker::make('generated_at')
                        ->label(__('dberp.fields.generated_at'))
                        ->disabled(),
                    DateTimePicker::make('processed_at')
                        ->label(__('dberp.fields.processed_at')),
                    Textarea::make('remark')
                        ->label(__('dberp.fields.remark'))
                        ->rows(3)
                        ->columnSpanFull(),
                ])
                ->columns(3),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('generated_at', 'desc')
            ->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('system_suggested_quantity')->label(__('dberp.fields.system_suggested_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('adjusted_quantity')->label(__('dberp.fields.adjusted_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('trigger_reason')->label(__('dberp.fields.trigger_reason'))->limit(20),
                TextColumn::make('status')
                    ->label(__('dberp.fields.replenishment_suggestion_status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.inventory_replenishment_suggestion_status')[$state] ?? (string) $state),
                TextColumn::make('generated_at')->label(__('dberp.fields.generated_at'))->dateTime(),
                TextColumn::make('processed_at')->label(__('dberp.fields.processed_at'))->dateTime(),
            ])
            ->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.replenishment_suggestion_status'))->options(__('dberp.options.inventory_replenishment_suggestion_status')),
            ])
            ->recordActions([
                Action::make('generate_purchase_request')
                    ->label(__('dberp.actions.generate_purchase_request'))
                    ->requiresConfirmation()
                    ->visible(fn (DberpInventoryReplenishmentSuggestion $record): bool => in_array($record->status, [InventoryReplenishmentSuggestionStatus::Pending->value, InventoryReplenishmentSuggestionStatus::Reviewed->value], true))
                    ->action(function (DberpInventoryReplenishmentSuggestion $record): void {
                        $request = app(PurchaseRequestGenerationService::class)->createFromReplenishmentSuggestion($record);

                        redirect(DberpPurchaseRequestResource::getUrl('edit', ['record' => $request]));
                    }),
                EditAction::make(),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpInventoryReplenishmentSuggestions::route('/'),
            'edit' => EditDberpInventoryReplenishmentSuggestion::route('/{record}/edit'),
        ];
    }

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

    public static function canCreate(): bool
    {
        return false;
    }

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

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

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