<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Form\Type;

use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Form\Type\DataTransformer\AddressToIdDataTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Form type for picking an address.
 *
 * In the UI, this resolve to a vuejs component which will insert the created address id into the
 * hidden's value. It will also allow to edit existing addresses without changing the id.
 *
 * In every page where this component is shown, you must include the required module:
 *
 * ```twig
 * {% block js %}
 *     {{ encore_entry_script_tags('mod_input_address') }}
 * {% endblock %}
 *
 * {% block css %}
 *     {{ encore_entry_link_tags('mod_input_address') }}
 * {% endblock %}
 * ```
 */
final class PickAddressType extends AbstractType
{
    public function __construct(private readonly AddressToIdDataTransformer $addressToIdDataTransformer, private readonly TranslatorInterface $translator) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer($this->addressToIdDataTransformer);
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['uniqid'] = $view->vars['attr']['data-input-address'] = \uniqid('input_address_');
        $view->vars['attr']['data-use-valid-from'] = (int) $options['use_valid_from'];
        $view->vars['attr']['data-use-valid-to'] = (int) $options['use_valid_to'];
        $view->vars['attr']['data-button-text-create'] = $this->translator->trans($options['button_text_create']);
        $view->vars['attr']['data-button-text-update'] = $this->translator->trans($options['button_text_update']);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => Address::class,
            'use_valid_to' => false,
            'use_valid_from' => false,
            'button_text_create' => 'Create an address',
            'button_text_update' => 'Update address',

            // reset default from hidden type
            'required' => true,
            'error_bubbling' => false,
        ]);
    }

    public function getParent()
    {
        return HiddenType::class;
    }
}
