<?php

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

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

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

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

        $this->label('Tambah Penyesuaian')
            ->color('gray')
            ->button()
            ->outlined()
            ->modalWidth(Width::Large)
            ->extraAttributes([
                'class' => 'w-full flex justify-center',
            ])
            ->schema([
                Hidden::make('payroll_id'),

                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))),
            ])
            ->action(function (array $data) {
                $payroll = Payroll::find($data['payroll_id']);

                if ($payroll) {
                    $payroll->adjustments()->create([
                        'type' => $data['type'],
                        'description' => $data['description'],
                        'amount' => $data['amount'],
                    ]);
                }
            })
            ->successNotification(SystemNotification::create());
    }
}
