<?php

namespace App\Filament\Resources\GrnResource\Pages;

use App\Filament\Resources\GrnResource;
use App\Models\Inventory\Grn;
use App\Models\Inventory\GrnItem;
use App\Services\CurrentContext;
use App\Support\Quantity;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;

/**
 * The confirm/delete transitions here are the same Action objects the table
 * row uses (GrnResource::transitionActions()), minus the redundant "view"
 * link, so a GRN can be confirmed or deleted from its own detail page
 * instead of only from the list.
 */
class ViewGrn extends ViewRecord
{
    protected static string $resource = GrnResource::class;

    public function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make()->schema([
                TextEntry::make('grn_number')->label('GRN #'),
                TextEntry::make('branch.name'),
                TextEntry::make('supplier.name')->placeholder('—'),
                TextEntry::make('grnStatus.name')
                    ->label('Status')
                    ->badge()
                    ->color(fn (Grn $record): string => $record->grnStatus?->color ?? 'gray'),
                TextEntry::make('reference')->placeholder('—'),
                TextEntry::make('confirmedBy.name')->label('Confirmed by')->placeholder('—'),
                TextEntry::make('note')->columnSpanFull(),
            ])->columns(3),
            Section::make('Items')->schema([
                RepeatableEntry::make('items')
                    ->schema([
                        TextEntry::make('product.name')->label('Product'),
                        TextEntry::make('quantity')
                            ->formatStateUsing(fn ($state, GrnItem $record): string => Quantity::format($state, $record->unit)),
                        TextEntry::make('unit_cost')->label('Purchase Price')->money(fn () => app(CurrentContext::class)->currencyCode())->placeholder('—'),
                        // Kept on the line so the price this GRN pushed onto the
                        // product stays readable after later GRNs move it on.
                        TextEntry::make('sale_price')->label('Selling Price')->money(fn () => app(CurrentContext::class)->currencyCode())->placeholder('—'),
                    ])
                    ->columns(4)
                    ->columnSpanFull(),
            ]),
        ]);
    }

    protected function getHeaderActions(): array
    {
        return collect(GrnResource::transitionActions())
            ->reject(fn ($action) => $action->getName() === 'view')
            ->all();
    }
}
