<?php

declare(strict_types=1);

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;

/**
 * Plugin implementation of the map_action.
 */
#[MapAction(
  id: 'navigate_action',
  label: new TranslatableMarkup('Navigate to URL'),
  description: new TranslatableMarkup('Clicking on this item navigates the user to a URL.'),
  is_system: FALSE,
)]
final class NavigateAction extends MapActionPluginBase {

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

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'url' => '',
      'new_tab' => FALSE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $form['url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('URL'),
      '#description' => $this->t('The URL to navigate to.'),
      '#required' => TRUE,
      '#default_value' => $this->configuration['url'] ?? '',
    ];

    $form['new_tab'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Open in new tab'),
      '#description' => $this->t('Open the URL in a new tab.'),
      '#default_value' => $this->configuration['new_tab'] ?? FALSE,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state): void {
    $url = $form_state->getValue('url');
    if (!empty($url)) {
      $parsed = parse_url($url);
      if (!$parsed) {
        $form_state->setErrorByName('url', 'The URL is not valid.');
      }
    }
  }

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

  /**
   * {@inheritdoc}
   */
  public function getActionConfiguration(): array {
    return $this->getConfiguration();
  }

}
