<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Url;
use Drupal\simple_interactive_maps\InteractiveMapInterface;
use Drupal\simple_interactive_maps\MapActionPluginManager;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Returns responses for Simple Interactive Maps routes.
 */
final class MapRegionController extends ControllerBase implements ContainerInjectionInterface {

  public function __construct(protected MapActionPluginManager $actionPluginManager) {}

  /**
   * Builds the response.
   */
  public function __invoke(?InteractiveMapInterface $interactive_map = NULL): array {
    if (!($interactive_map instanceof InteractiveMapInterface)) {
      throw new HttpException(404, 'Interactive map not found.');
    }

    $regions = $interactive_map->getRegions();

    uasort($regions, function ($a, $b) {
      return strnatcasecmp($a['label'], $b['label']);
    });

    $build = [];

    $build['table_link'] = [
      '#type' => 'link',
      '#title' => $this->t('Table view'),
      '#url' => Url::fromRoute('simple_interactive_maps.map_regions_table_form', ['interactive_map' => $interactive_map->id()]),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];

    $build['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h2',
      '#value' => $this->t('Click on a region to edit it'),
    ];

    $build['map'] = [
      '#theme' => 'interactive_map',
      '#map' => $interactive_map,
      '#map_id' => $interactive_map->id(),
      '#map_context' => 'region_editor',
    ];

    $build['note'] = [
      '#type' => 'item',
      '#markup' => $this->t('Switch to the table view to edit hidden regions.'),
    ];

    return $build;
  }

}
