<?php

namespace App\Filament\Resources\StockBatchResource\Pages;

use App\Filament\Resources\StockBatchResource;
use App\Models\Inventory\StockBatch;
use App\Models\StockMovement;
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 ViewStockBatch extends ViewRecord
{
    protected static string $resource = StockBatchResource::class;

    public function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make()->schema([
                TextEntry::make('internal_batch_number'),
                TextEntry::make('product.name'),
                TextEntry::make('branch.name'),
                TextEntry::make('available_quantity')
                    ->formatStateUsing(fn ($state, StockBatch $record): string => Quantity::format($state, $record->product?->baseUnit)),
                TextEntry::make('expiry_date')->date()->placeholder('—'),
                TextEntry::make('status.name')->badge()->color(fn () => $this->record->status?->color ?? 'gray'),
            ])->columns(3),
            Section::make('Movement History')->schema([
                RepeatableEntry::make('movements')
                    ->getStateUsing(fn () => StockMovement::with('unit')->where('stock_batch_id', $this->record->id)->orderByDesc('created_at')->get())
                    ->schema([
                        TextEntry::make('movementType.name')->label('Type'),
                        TextEntry::make('quantity_change')
                            ->formatStateUsing(fn ($state, StockMovement $record): string => Quantity::format($state, $record->unit)),
                        TextEntry::make('created_at')->dateTime(),
                    ])
                    ->columns(3)
                    ->columnSpanFull(),
            ]),
        ]);
    }
}
