<?php

namespace App\Filament\Resources\TintoreriaResource\Pages;

use App\Filament\Resources\TintoreriaResource;
use Filament\Actions;
use Filament\Forms;
use Filament\Resources\Pages\EditRecord;

class EditTintoreria extends EditRecord
{
    protected static string $resource = TintoreriaResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make(),

            Actions\Action::make('agregarRecepcion')
                ->label('Agregar recepción')
                ->modalHeading('Agregar Recepción')
                ->disabled(fn (): bool => ($this->getRecord()->faltantes ?? 0) <= 0)
                ->form([
                    Forms\Components\DatePicker::make('fecha_recepcion')->default(now())->required(),
                    Forms\Components\TextInput::make('cantidad')
                        ->numeric()
                        ->required()
                        ->minValue(1)
                        ->maxValue(fn () => $this->getRecord()->faltantes ?? 0)
                        ->helperText(fn () => 'Máximo: ' . ($this->getRecord()->faltantes ?? 0))
                        ->default(fn () => $this->getRecord()->faltantes ?? 0),
                    Forms\Components\TextInput::make('prendas_defectuosas')
                        ->numeric()
                        ->minValue(0)
                        ->maxValue(fn ($get) => (int) ($get('cantidad') ?? 0))
                        ->helperText('Opcional. Se restará del total recibido.'),
                    Forms\Components\Textarea::make('notas'),
                ])
                ->action(function (array $data): void {
                    $record = $this->getRecord();

                    try {
                        \App\Models\Recepcion::create([
                            'referencia_type' => \App\Models\Tintoreria::class,
                            'referencia_id' => $record->id,
                            'cantidad' => (int) $data['cantidad'],
                            'prendas_defectuosas' => (int) ($data['prendas_defectuosas'] ?? 0),
                            'fecha_recepcion' => $data['fecha_recepcion'],
                            'notas' => $data['notas'] ?? null,
                        ]);

                        \Filament\Notifications\Notification::make()
                            ->success()
                            ->title('Recepción registrada')
                            ->body('La recepción se creó correctamente.')
                            ->send();
                    } catch (\Illuminate\Validation\ValidationException $e) {
                        \Filament\Notifications\Notification::make()
                            ->danger()
                            ->title('Error')
                            ->body($e->validator->errors()->first() ?? 'Error al crear la recepción.')
                            ->send();
                    } catch (\Throwable $e) {
                        \Filament\Notifications\Notification::make()
                            ->danger()
                            ->title('Error')
                            ->body($e->getMessage())
                            ->send();
                    }

                    // Refrescar la página para ver cambios
                    $this->redirect(route('filament.admin.resources.tintorerias.edit', ['record' => $record->id]));
                }),

            // Reprocesos: registrar reproceso como ajuste
            Actions\Action::make('reprocesos')
                ->label('Reprocesos')
                ->modalHeading('Registrar Reproceso')
                ->form([
                    Forms\Components\TextInput::make('cantidad')
                        ->label('Cantidad a reprocesar')
                        ->numeric()
                        ->required()
                        ->minValue(1)
                        ->maxValue(fn () => $this->getRecord()->recibido_total ?? 0)
                        ->helperText(fn () => 'Máximo: ' . ($this->getRecord()->recibido_total ?? 0)),
                    Forms\Components\Textarea::make('notas'),
                ])
                ->action(function (array $data): void {
                    $record = $this->getRecord();

                    $cantidad = (int) ($data['cantidad'] ?? 0);

                    try {
                        $record->registerReproceso($cantidad, $data['notas'] ?? null, auth()->id() ?? null);

                        \Filament\Notifications\Notification::make()->success()->title('Reproceso registrado')->body('Se registró el reproceso correctamente.')->send();
                    } catch (\Illuminate\Validation\ValidationException $e) {
                        \Filament\Notifications\Notification::make()->danger()->title('Error')->body($e->validator->errors()->first() ?? 'Error al registrar reproceso.')->send();
                    } catch (\Throwable $e) {
                        \Filament\Notifications\Notification::make()->danger()->title('Error')->body($e->getMessage())->send();
                    }

                    $this->redirect(route('filament.admin.resources.tintorerias.edit', ['record' => $record->id]));
                }),

            // Cobros: descontar inventario y registrar cobro
            Actions\Action::make('cobros')
                ->label('Cobros')
                ->modalHeading('Registrar Cobro')
                ->form([
                    Forms\Components\TextInput::make('cantidad')
                        ->label('Cantidad')
                        ->numeric()
                        ->required()
                        ->minValue(1),
                    Forms\Components\TextInput::make('valor')
                        ->label('Valor a descontar')
                        ->numeric()
                        ->required()
                        ->minValue(0),
                    Forms\Components\Textarea::make('notas'),
                ])
                ->action(function (array $data): void {
                    $record = $this->getRecord();

                    $cantidad = (int) ($data['cantidad'] ?? 0);
                    $valor = (float) ($data['valor'] ?? 0);

                    try {
                        $record->registerCobro($cantidad, $valor, $data['notas'] ?? null, auth()->id() ?? null);

                        \Filament\Notifications\Notification::make()->success()->title('Cobro registrado')->body('Se descontó del inventario y se registró el cobro.')->send();
                    } catch (\Illuminate\Validation\ValidationException $e) {
                        \Filament\Notifications\Notification::make()->danger()->title('Error')->body($e->validator->errors()->first() ?? 'Error al registrar cobro.')->send();
                    } catch (\Throwable $e) {
                        \Filament\Notifications\Notification::make()->danger()->title('Error')->body($e->getMessage())->send();
                    }

                    $this->redirect(route('filament.admin.resources.tintorerias.edit', ['record' => $record->id]));
                }),
        ];
    }
}
