<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpInventoryWarnings;

use App\Business\Inventory\InventoryWarningService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\Concerns\HasDberpExportAction;
use App\Filament\Resources\DberpInventoryBalances\DberpInventoryBalanceResource;
use App\Filament\Resources\DberpInventoryWarnings\Pages\ListDberpInventoryWarnings;
use App\Models\DberpInventoryBalance;
use App\Models\DberpProductCategory;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use App\Support\DberpProductSkuSelectOptions;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Resources\Resource;
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 UnitEnum;

class DberpInventoryWarningResource extends Resource
{
    use HasDberpExportAction;
    use InteractsWithDberpPermissions;

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

    protected static ?int $navigationSort = 30;

    public static function form(Schema $schema): Schema
    {
        return $schema;
    }

    public static function getEloquentQuery(): Builder
    {
        return app(InventoryWarningService::class)->query();
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('available_quantity', 'asc')
            ->columns([
                TextColumn::make('product.code')
                    ->label(__('dberp.fields.product_code'))
                    ->searchable(),
                TextColumn::make('product.name')
                    ->label(__('dberp.fields.product_name'))
                    ->searchable(),
                TextColumn::make('product.category.name')
                    ->label(__('dberp.fields.category')),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse')),
                TextColumn::make('realtime_quantity')
                    ->label(__('dberp.fields.realtime_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('available_quantity')
                    ->label(__('dberp.fields.available_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('safety_stock')
                    ->label(__('dberp.fields.safety_stock'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('warning_type')
                    ->label(__('dberp.fields.warning_type'))
                    ->badge()
                    ->state(fn (DberpInventoryBalance $record): string => app(InventoryWarningService::class)->warningTypeLabel($record)),
                TextColumn::make('last_moved_at')
                    ->label(__('dberp.fields.last_moved_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('category_id')
                    ->label(__('dberp.fields.category'))
                    ->options(fn (): array => DberpProductCategory::query()->orderBy('sort_order')->orderBy('id')->pluck('name', 'id')->all())
                    ->query(fn ($query, array $data) => $query->when($data['value'] ?? null, fn ($builder, $value) => $builder->whereHas('product', fn ($productQuery) => $productQuery->where('category_id', $value)))),
                SelectFilter::make('warning_type')
                    ->label(__('dberp.fields.warning_type'))
                    ->options([
                        'low_stock' => __('dberp.options.inventory_warning_type.low_stock'),
                        'zero_stock' => __('dberp.options.inventory_warning_type.zero_stock'),
                    ])
                    ->query(function ($query, array $data): void {
                        $warningType = $data['value'] ?? null;

                        if ($warningType === 'low_stock') {
                            $query->lowStock();
                        }

                        if ($warningType === 'zero_stock') {
                            $query->zeroStock();
                        }
                    }),
            ])
            ->headerActions([
                static::makeExportAction('inventory-warning-report'),
            ])
            ->recordActions([
                Action::make('adjustSafetyStock')
                    ->label(__('dberp.actions.adjust_safety_stock'))
                    ->url(fn (DberpInventoryBalance $record): string => DberpInventoryBalanceResource::getUrl('edit', ['record' => $record])),
            ]);
    }

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

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

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

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