<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseInquiries\RelationManagers;

use App\Support\DberpDocumentLineSpecPresentation;
use App\Support\DberpNumberFormatter;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;

class ItemsRelationManager extends RelationManager
{
    protected static string $relationship = 'items';

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

    public function form(Schema $schema): Schema
    {
        return $schema->components([]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) => $query->with([
                'product',
                'warehouse',
                'purchaseRequestItem',
                ...DberpDocumentLineSpecPresentation::eagerLoadsForDocumentLines(['baseUnit', 'auxiliaryUnit']),
            ]))
            ->defaultSort('sort_order')
            ->columns([
                TextColumn::make('product.name')
                    ->label(__('dberp.fields.product')),
                TextColumn::make('product_sku_name')
                    ->label(__('dberp.fields.product_spec'))
                    ->state(fn ($record): string => DberpDocumentLineSpecPresentation::lineSpecSummary($record)),
                TextColumn::make('inquiry_quantity')
                    ->label(__('dberp.fields.inquiry_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('warehouse.name')
                    ->label(__('dberp.fields.warehouse')),
                TextColumn::make('purchaseRequestItem.remaining_quantity')
                    ->label(__('dberp.fields.remaining_quantity'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('remark')
                    ->label(__('dberp.fields.remark'))
                    ->limit(40),
            ])
            ->headerActions([])
            ->recordActions([])
            ->toolbarActions([]);
    }
}
