<?php

declare(strict_types=1);

namespace Apexl\Io\User\Display\FormBuilders;

use Apexl\Io\Component\Collections\ComponentCollection;
use Apexl\Io\Component\Factories\GenericComponentFactory;
use Apexl\Io\FormBuilder\ComponentFactories\FormComponentFactory;
use Apexl\Io\FormBuilder\ComponentFactories\FormFieldComponentFactory;
use Apexl\Io\FormBuilder\Components\Form;
use Apexl\Io\FormBuilder\Components\FormKitField\HiddenFormKitField;
use Apexl\Io\FormBuilder\FormBuilders\FormBuilder;
use Apexl\Io\Services\RouteUrls;
use Apexl\Io\Services\VariableManager;
use Apexl\Io\Validation\ValidationRules\IsString;

readonly class LoginWithNfcFormBuilder extends FormBuilder
{
    public function __construct(
        private VariableManager $variableManager,
        FormFieldComponentFactory $fieldComponentFactory,
        GenericComponentFactory $componentFactory,
        RouteUrls $routeUrls,
        FormComponentFactory $formComponentFactory,
        string $formClass = Form::class
    ) {
        parent::__construct(
            $fieldComponentFactory,
            $componentFactory,
            $routeUrls,
            $formComponentFactory,
            $formClass
        );
    }

    protected function init(): void
    {
        parent::init();
        $this->form
            ->setTitle($this->variableManager->get('user_login_description_text') ?? 'Sign in with your email address.')
            ->setSubmitText($this->variableManager->get('user_login_nfc_submit_text') ?? 'Touch to complete login')
            ->addClass('login-form');

        if ($this->variableManager->get('user_login_include_clear_button') ?? true) {
            $this->form->includeClearButton()->setClearButtonText(
                $this->variableManager->get('user_login_include_clear_button_text') ?? 'Cancel'
            );
        }
    }

    protected function formAction(): string
    {
        return $this->routeUrls->url('user.login.nfc');
    }

    protected function components(ComponentCollection $components): ComponentCollection
    {
        $components->add($this->field(HiddenFormKitField::class, 'redirect'));

        $components->add(
            $this->field(HiddenFormKitField::class, 'nfc_key')
                ->addValidation(IsString::class)
                ->isRequired(),
        );

        return $components;
    }

    private function hasNfcKey(): bool
    {
        return !!$this->form->getValue('nfc_key');
    }
}


