<?php

namespace App\Filament\Resources\ConfeccionResource\RelationManagers;

use Filament\Forms;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;

class CobrosRelationManager extends RelationManager
{
    protected static string $relationship = 'cobros';
    protected static ?string $recordTitleAttribute = 'id';

    public function table(Tables\Table $table): Tables\Table
    {
        return $table
            ->columns([
                TextColumn::make('id')->label('#'),
                TextColumn::make('cantidad')->label('Cantidad'),
                TextColumn::make('valor')->label('Valor')->money('USD'),
                TextColumn::make('usuario.name')->label('Usuario'),
                TextColumn::make('notas')->limit(80)->wrap(),
                TextColumn::make('created_at')->label('Fecha')->dateTime(),
            ])
            ->filters([])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->form([
                        \Filament\Forms\Components\TextInput::make('cantidad')
                            ->label('Cantidad de Prendas')
                            ->numeric()
                            ->required()
                            ->minValue(1)
                            ->helperText('Prendas a descontar del inventario'),
                        \Filament\Forms\Components\TextInput::make('valor')
                            ->label('Valor del Cobro')
                            ->numeric()
                            ->required()
                            ->minValue(0)
                            ->prefix('$')
                            ->step(0.01),
                        \Filament\Forms\Components\Textarea::make('notas')
                            ->label('Notas')
                            ->rows(3),
                    ])
                    ->action(function (array $data, RelationManager $livewire) {
                        $owner = $livewire->getOwnerRecord();
                        
                        try {
                            $owner->registerCobro(
                                (int) $data['cantidad'], 
                                (float) $data['valor'], 
                                $data['notas'] ?? null, 
                                auth()->id()
                            );
                            
                            \Filament\Notifications\Notification::make()
                                ->success()
                                ->title('Cobro registrado correctamente')
                                ->body("Se descontaron {$data['cantidad']} prendas del inventario.")
                                ->send();
                                
                            // Refrescar la tabla
                            $livewire->dispatch('refresh');
                            
                        } catch (\Illuminate\Validation\ValidationException $e) {
                            \Filament\Notifications\Notification::make()
                                ->danger()
                                ->title('Error de validación')
                                ->body($e->getMessage())
                                ->persistent()
                                ->send();
                            throw $e;
                        } catch (\Throwable $e) {
                            \Filament\Notifications\Notification::make()
                                ->danger()
                                ->title('Error al registrar cobro')
                                ->body($e->getMessage())
                                ->persistent()
                                ->send();
                            throw $e;
                        }
                    })
                    ->modalHeading('Registrar Cobro')
                    ->modalSubmitActionLabel('Registrar')
                    ->successNotificationTitle('Cobro registrado'),
            ])
            ->actions([])
            ->bulkActions([]);
    }
}
