<?php

namespace App\Filament\Tenant\Resources\LaborResource\RelationManagers;

use App\Models\Tenant\Part;
use Filament\Actions;
use Filament\Forms;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;

class DefaultPartsRelationManager extends RelationManager
{
    protected static string $relationship = 'laborParts';

    protected static ?string $title = 'Piese implicite';

    public function form(Schema $schema): Schema
    {
        return $schema->components([
            Forms\Components\Select::make('part_id')
                ->label('Piesă')
                ->options(fn () => Part::where('is_active', true)
                    ->get()
                    ->mapWithKeys(fn ($p) => [$p->id => "{$p->name} " . ($p->article ? "[{$p->article}]" : '')])
                    ->toArray())
                ->searchable()
                ->required()
                ->live()
                ->afterStateUpdated(function ($state, Set $set) {
                    if ($state && $p = Part::find($state)) {
                        $set('unit', $p->unit);
                    }
                }),
            Forms\Components\TextInput::make('qty')->label('Cantitate')->numeric()->default(1)->required(),
            Forms\Components\TextInput::make('unit')->label('UM')->default('buc')->maxLength(16),
        ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('part.name')
            ->columns([
                Tables\Columns\TextColumn::make('part.name')->label('Piesă')->wrap(),
                Tables\Columns\TextColumn::make('part.article')->label('Cod')->placeholder('—'),
                Tables\Columns\TextColumn::make('qty')->label('Cant.')->alignRight(),
                Tables\Columns\TextColumn::make('unit')->label('UM'),
            ])
            ->headerActions([Actions\CreateAction::make()])
            ->actions([Actions\EditAction::make(), Actions\DeleteAction::make()])
            ->emptyStateHeading('Nicio piesă implicită')
            ->emptyStateDescription('Adaugă piesele care se montează de obicei la această manoperă — se adaugă automat în fișă când selectezi manopera.');
    }
}
