<?php

namespace App\Filament\Resources\TintoreriaResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Tables\Actions\DeleteAction;
use Filament\Tables\Actions\EditAction;

class RecepcionesRelationManager extends RelationManager
{
    protected static string $relationship = 'recepciones';
    protected static ?string $recordTitleAttribute = 'id';

    public function form(Forms\Form $form): Forms\Form
    {
        return $form->schema([
            DateTimePicker::make('fecha_recepcion')->required(),
            TextInput::make('cantidad')
                ->numeric()
                ->required()
                ->minValue(1)
                ->maxValue(fn () => $this->getOwnerRecord()?->faltantes ?? 0)
                ->helperText(fn () => 'Máximo: ' . ($this->getOwnerRecord()?->faltantes ?? 0)),

            TextInput::make('prendas_defectuosas')
                ->label('Faltantes')
                ->numeric()
                ->minValue(0)
                ->maxValue(fn ($get) => (int) ($get('cantidad') ?? 0))
                ->helperText('Opcional. Se restará del total recibido.'),

            Textarea::make('notas'),
        ]);
    }

    public function table(Tables\Table $table): Tables\Table
    {
        return $table
            ->columns([
                TextColumn::make('id')->label('#'),
                TextColumn::make('fecha_recepcion')->dateTime()->label('Fecha'),
                TextColumn::make('cantidad')->label('Cantidad'),
                TextColumn::make('prendas_defectuosas')->label('Faltantes'),
                TextColumn::make('usuario.name')->label('Usuario'),
                TextColumn::make('notas')->limit(50)->wrap(),
                TextColumn::make('created_at')->dateTime()->label('Creado'),
            ])
            ->headerActions([])
            ->actions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->bulkActions([]);
    }
}
