<?php

namespace Drupal\simple_interactive_maps\Plugin\MapAction;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\simple_interactive_maps\Attribute\MapAction;
use Drupal\simple_interactive_maps\MapActionPluginBase;
use Drupal\simple_interactive_maps\MapDataLoader;

/**
 * AJAX load another map to replace this one.
 */
#[MapAction(
  id: 'ajax_load_map',
  label: new TranslatableMarkup('Load Map'),
  description: new TranslatableMarkup('Load another map using AJAX.'),
  is_system: FALSE,
)]
class LoadMap extends MapActionPluginBase {

  /**
   * {@inheritDoc}
   */
  public function defaultConfiguration(): array {
    return [
      'target_map_id' => '',
    ];
  }

  /**
   * {@inheritDoc}
   */
  public function getActionLibrary(): string {
    return 'simple_interactive_maps/load_map';
  }

  /**
   * {@inheritDoc}
   */
  public function getActionConfiguration(): array {
    $config = $this->configuration;

    return [
      'target_map_id' => $config['target_map_id'],
    ];
  }

  /**
   * {@inheritDoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
    $mapOptions = MapDataLoader::getMapOptions();

    $form['target_map_id'] = [
      '#type' => 'select',
      '#title' => $this->t('Target Map'),
      '#description' => $this->t('Select the map to load.'),
      '#options' => $mapOptions,
      '#default_value' => $this->configuration['target_map_id'],
      '#required' => TRUE,
      '#empty_option' => $this->t('- Select -'),
    ];

    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state): void {}

  /**
   * {@inheritDoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
    $this->configuration['target_map_id'] = $form_state->getValue('target_map_id');
  }

}
