<?php

namespace App\Filament\Pages\Auth;

use App\Enums\UserRoleEnum;
use App\Models\Currency;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;

class Register extends \Filament\Pages\Auth\Register
{

    public function mount(): void
    {
        if (User::count() >  0) {
            redirect()->to('/login');
        }

        parent::mount(); // TODO: Change the autogenerated stub
    }

    public function getRegisterFormAction(): Action
    {
        if (User::count() > 0)
            return Action::make('redirect')
                ->action(fn () => redirect()->to('/'));

        return parent::getRegisterFormAction();
    }

    protected function mutateFormDataBeforeRegister(array $data): array
    {
        $data['role'] = UserRoleEnum::Admin->value;
        return parent::mutateFormDataBeforeRegister($data);
    }

    protected function getForms(): array
    {
        $fields= [
            Placeholder::make('disabled')
        ];

        if (User::count() == 0){
            $fields=[
                $this->getNameFormComponent(),
                $this->getEmailFormComponent(),
                $this->getPasswordFormComponent(),
                $this->getPasswordConfirmationFormComponent(),
                Select::make('currency_id')
                    ->label('Default Currency')
                    ->model(User::class)
                    ->options(Currency::all()->pluck('code_name', 'id'))
                    ->native(false)
                    ->preload()
                    ->required()
                    ->searchable(),
            ];
        }

        return [
            'form' => $this->form(
                $this->makeForm()
                    ->schema($fields)
                    ->statePath('data'),
            ),
        ];
    }
}
