<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpInventorySerialNumbers\RelationManagers;

use App\Business\Inventory\Enums\InventoryExceptionStatus;
use App\Business\Inventory\Enums\InventoryExceptionType;
use App\Filament\Resources\DberpInventoryExceptions\DberpInventoryExceptionResource;
use Filament\Actions\ViewAction;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

class InventorySerialNumberExceptionsRelationManager extends RelationManager
{
    protected static string $relationship = 'inventoryExceptions';

    public static function getTitle(Model $ownerRecord, string $pageClass): string
    {
        return __('dberp.relations.inventory_serial_number_exceptions');
    }

    protected static function getModelLabel(): ?string
    {
        return __('dberp.resources.inventory_exception.label');
    }

    protected static function getPluralModelLabel(): ?string
    {
        return __('dberp.relations.inventory_serial_number_exceptions');
    }

    public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
    {
        return DberpInventoryExceptionResource::canViewAny();
    }

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

    public function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) => $query->with(['warehouse', 'product']))
            ->defaultSort('occurred_at', 'desc')
            ->columns([
                TextColumn::make('title')
                    ->label(__('dberp.fields.title'))
                    ->searchable(),
                TextColumn::make('exception_type')
                    ->label(__('dberp.fields.exception_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryExceptionType::options()[$state] ?? (string) $state),
                TextColumn::make('status')
                    ->label(__('dberp.fields.exception_status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => InventoryExceptionStatus::options()[$state] ?? (string) $state),
                TextColumn::make('occurred_at')
                    ->label(__('dberp.fields.occurred_at'))
                    ->dateTime(),
            ])
            ->recordActions([
                ViewAction::make()
                    ->url(fn (Model $record): string => DberpInventoryExceptionResource::getUrl('edit', ['record' => $record]))
                    ->visible(fn (): bool => DberpInventoryExceptionResource::canViewAny()),
            ])
            ->emptyStateHeading(__('dberp.empty_states.inventory_serial_number_no_exceptions'))
            ->paginated([10, 25, 50]);
    }
}
