<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Ajax\EditorDialogSave;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Simple Interactive Maps form.
 */
final class EditorDialogForm extends FormBase {

  public function __construct(protected EntityTypeManagerInterface $entityTypeManager) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $entityTypeManager = $container->get('entity_type.manager');
    return new EditorDialogForm($entityTypeManager);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'simple_interactive_maps_editor_dialog';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {

    $maps = $this->entityTypeManager->getStorage('interactive_map')->loadMultiple();

    $mapOptions = [];

    foreach ($maps as $map) {
      $mapOptions[$map->id()] = $map->label();
    }

    uasort($mapOptions, 'strnatcasecmp');

    $form['map'] = [
      '#type' => 'select',
      '#title' => $this->t('Select the map to insert'),
      '#options' => $mapOptions,
      '#required' => TRUE,
      '#empty_option' => $this->t('- Select -'),
    ];

    $form['show_description'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show map description'),
      '#default_value' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
      'submit' => [
        '#type' => 'submit',
        '#value' => $this->t('Embed map'),
        '#ajax' => [
          'callback' => '::submitForm',
          'event' => 'click',
        ],
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state): void {
    // @todo Validate the form here.
    // Example:
    // @code
    //   if (mb_strlen($form_state->getValue('message')) < 10) {
    //     $form_state->setErrorByName(
    //       'message',
    //       $this->t('Message should be at least 10 characters.'),
    //     );
    //   }
    // @endcode
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): AjaxResponse {
    $response = new AjaxResponse();
    $mapId = $form_state->getValue('map');

    $map = $this->entityTypeManager->getStorage('interactive_map')->load($mapId);

    $values['settings']['map'] = $mapId;
    $values['settings']['map_title'] = $map->label();
    $values['settings']['show_description'] = $form_state->getValue('show_description');

    $response->addCommand(new EditorDialogSave($values));
    $response->addCommand(new CloseModalDialogCommand());

    return $response;
  }

}
