<?php

namespace App\Filament\Resources\Finance\Payrolls\Actions;

use App\Enums\SalaryAdjustmentType;
use App\Filament\Support\SystemNotification;
use App\Models\PayrollAdjustment;
use Filament\Actions\Action;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\TextInput;
use Filament\Support\Enums\Width;

class EditAdjustmentAction extends Action
{
    public static function getDefaultName(): ?string
    {
        return 'editAdjustment';
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->label('Ubah')
            ->icon('heroicon-m-pencil-square')
            ->iconButton()
            ->color('warning')
            ->modalWidth(Width::Large)
            ->schema([
                Radio::make('type')
                    ->label('Tipe')
                    ->options(SalaryAdjustmentType::options())
                    ->required()
                    ->inline(),

                TextInput::make('description')
                    ->label('Keterangan')
                    ->placeholder('Bonus lembur / Potongan kasbon')
                    ->required()
                    ->maxLength(100)
                    ->autofocus()
                    ->autocomplete(false),

                TextInput::make('amount')
                    ->label('Nominal')
                    ->placeholder('0')
                    ->required()
                    ->autocomplete(false)
                    ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                    ->prefix('Rp')
                    ->dehydrateStateUsing(fn ($state) => (int) str()->replace('.', '', (string) ($state ?? 0))),
            ])
            ->mountUsing(function ($form, $arguments) {
                $adjustment = PayrollAdjustment::findOrFail($arguments['adjustment_id']);

                $form->fill([
                    'type' => $adjustment->type->value,
                    'description' => $adjustment->description,
                    'amount' => $adjustment->amount,
                ]);
            })
            ->action(function (array $data, array $arguments) {
                $adjustment = PayrollAdjustment::findOrFail($arguments['adjustment_id']);

                $adjustment->update([
                    'type' => $data['type'],
                    'description' => $data['description'],
                    'amount' => $data['amount'],
                ]);
            })
            ->successNotification(SystemNotification::update());
    }
}
