<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Configuration\Form\Type;

use InPost\International\Configuration\Enum\ClosestPointSearchMode;
use InPost\International\Configuration\Form\Type\Checkout\GoogleMapsGeocoderOptionsType;
use InPost\International\Configuration\Message\UpdateCheckoutConfigurationCommand;
use InPost\International\Enum\Form\Type\EnumType;
use InPost\International\Form\EventListener\UseInitialDataListener;
use InPost\International\Geocoding\GoogleMaps\GoogleMapsGeocoder;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class CheckoutConfigurationType extends AbstractType
{
    /**
     * @var TranslatorInterface
     */
    private $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('closestPointSerachMode', EnumType::class, [
                'class' => ClosestPointSearchMode::class,
                'label' => $this->translator->trans('Closest pickup point search mode', [], 'Modules.Inpostinternational.Configuration'),
                'attr' => [
                    'class' => 'js-inpost-intl-closest-point-search-mode-choice',
                    'autocomplete' => 'off',
                ],
            ])
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
                $data = $event->getData();

                if (!$data instanceof UpdateCheckoutConfigurationCommand) {
                    return;
                }

                if (ClosestPointSearchMode::GoogleMapsGeocoder() !== $data->getClosestPointSerachMode()) {
                    return;
                }

                $this->addGoogleMapsGeocoderOptions($event->getForm());
            });

        $builder->get('closestPointSerachMode')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $form = $event->getForm();
            $data = $form->getData();

            if (!$data instanceof ClosestPointSearchMode) {
                return;
            }

            if (ClosestPointSearchMode::GoogleMapsGeocoder() === $data) {
                $this->addGoogleMapsGeocoderOptions($form->getParent());
            } else {
                $parent = $form->getParent();
                $command = $parent->getData();

                $parent->remove('geocoderConfig');
                if ($command instanceof UpdateCheckoutConfigurationCommand) {
                    $command->removeGeocoderConfig(GoogleMapsGeocoder::ID);
                }
            }
        });
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => UpdateCheckoutConfigurationCommand::class,
        ]);
    }

    private function addGoogleMapsGeocoderOptions(FormInterface $form): void
    {
        $child = $form->getConfig()
            ->getFormFactory()
            ->createNamedBuilder('geocoderConfig', GoogleMapsGeocoderOptionsType::class, null, [
                'property_path' => sprintf('geocoderConfigs[%s]', GoogleMapsGeocoder::ID),
                'label' => false,
            ])
            ->setAutoInitialize(false)
            ->addEventSubscriber(new UseInitialDataListener())
            ->getForm();

        $form->add($child);
    }
}
