<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\Plugin\Block;

use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\simple_interactive_maps\InteractiveMapInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides an interactive map block.
 */
#[Block(
  id: 'simple_interactive_maps_interactive_map',
  admin_label: new TranslatableMarkup('Interactive Map'),
  category: new TranslatableMarkup('Maps'),
)]
final class InteractiveMapBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Constructs the plugin instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    protected EntityTypeManagerInterface $entityTypeManager,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
    return new self(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration(): array {
    return [
      'map' => '',
      'title' => '',
      'show_title' => TRUE,
      'show_description' => TRUE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state): array {
    $mapConfigs = $this->entityTypeManager->getStorage('interactive_map')->loadMultiple();

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

    uasort($mapOptions, function ($a, $b) {
      return strcasecmp($a, $b);
    });

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

    $form['show_description'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show description'),
      '#default_value' => $this->configuration['show_description'],
      '#description' => $this->t("Show the map's description text below the map."),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state): void {
    $this->configuration['map'] = $form_state->getValue('map');
    $this->configuration['show_description'] = $form_state->getValue('show_description');
  }

  /**
   * {@inheritdoc}
   */
  public function build(): array {
    $map = $this->entityTypeManager->getStorage('interactive_map')->load($this->configuration['map']);

    assert($map instanceof InteractiveMapInterface);
    if ($this->configuration['show_description']) {
      $description = [
        '#type' => 'processed_text',
        '#text' => $map->get('description')['value'],
        '#format' => $map->get('description')['format'],
      ];
    }
    else {
      $description = '';
    }

    $cacheTags = $map->getCacheTags();

    $build['map_content'] = [
      '#theme' => 'interactive_map_block',
      '#map' => [
        '#theme' => 'interactive_map',
        '#map' => $map,
        '#show_description' => FALSE,
      ],
      '#show_description' => $this->configuration['show_description'],
      '#description' => $description,
      '#cache' => [
        'contexts' => ['url'],
        'tags' => $cacheTags,
      ],
    ];
    return $build;
  }

  /**
   * {@inheritDoc}
   */
  public function getCacheContexts(): array {
    return Cache::mergeContexts(parent::getCacheContexts(), ['url']);
  }

  /**
   * {@inheritDoc}
   */
  public function getCacheTags(): array {
    $map = $this->entityTypeManager->getStorage('interactive_map')->load($this->configuration['map']);
    assert($map instanceof InteractiveMapInterface);
    return Cache::mergeTags(parent::getCacheTags(), $map->getCacheTags());
  }

  /**
   * {@inheritDoc}
   */
  public function getCacheMaxAge(): int {
    return Cache::PERMANENT;
  }

}
