<?php

namespace App\Filament\Resources\PurchaseOrderResource\Pages;

use App\Filament\Resources\PurchaseOrderResource;
use App\Models\Inventory\Grn;
use App\Models\Purchasing\PurchaseOrderItem;
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;

class ViewPurchaseOrder extends ViewRecord
{
    protected static string $resource = PurchaseOrderResource::class;

    public function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make()->schema([
                TextEntry::make('po_number')->label('PO #'),
                TextEntry::make('supplier.name'),
                TextEntry::make('branch.name'),
                TextEntry::make('status.name')->badge()->color(fn () => $this->record->status?->color ?? 'gray'),
                TextEntry::make('expected_date')->date(),
                TextEntry::make('notes')->columnSpanFull(),
            ])->columns(3),
            Section::make('Items')->schema([
                RepeatableEntry::make('items')
                    ->schema([
                        TextEntry::make('product.name')->label('Product'),
                        TextEntry::make('ordered_quantity')
                            ->label('Ordered')
                            ->formatStateUsing(fn ($state, PurchaseOrderItem $record): string => Quantity::format($state, $record->unit)),
                        TextEntry::make('received_quantity')
                            ->label('Received')
                            ->formatStateUsing(fn ($state, PurchaseOrderItem $record): string => Quantity::format($state, $record->unit)),
                        TextEntry::make('unit_cost')->money(fn () => app(CurrentContext::class)->currencyCode()),
                    ])
                    ->columns(4)
                    ->columnSpanFull(),
            ]),
            Section::make('GRNs')->schema([
                RepeatableEntry::make('grns')
                    ->schema([
                        TextEntry::make('grn_number'),
                        TextEntry::make('grnStatus.name')
                            ->label('Status')
                            ->badge()
                            ->color(fn (Grn $record): string => $record->grnStatus?->color ?? 'gray'),
                    ])
                    ->columns(2)
                    ->columnSpanFull(),
            ])->visible(fn (): bool => $this->record->grns->isNotEmpty()),
        ]);
    }
}
