<?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 MapRegionTableController 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['map_link'] = [
      '#type' => 'link',
      '#title' => $this->t('Map View'),
      '#url' => Url::fromRoute('simple_interactive_maps.map_regions_form', ['interactive_map' => $interactive_map->id()]),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];

    $build['table'] = [
      '#type' => 'table',
      '#header' => ['Name', 'Action', 'Group', 'Actions'],
    ];

    $rows = [];
    foreach ($regions as $id => $region) {
      $plugin = $this->actionPluginManager->createInstance($region['action']['plugin_id']);

      $label = $region['label'];

      if ($region['hidden']) {
        $label .= ' (hidden)';
      }

      $rows[$id] = [
        'data-region-id' => $id,
        'data' => [
          $label,
          $plugin->label(),
          $region['group'],
          [
            'data' => [
              '#type' => 'link',
              '#title' => $this->t('Edit'),
              '#url' => Url::fromRoute('simple_interactive_maps.region_edit', [
                'interactive_map' => $interactive_map->id(),
                'region_id' => $id,
              ], [
                'query' => [
                  'destination' => Url::fromRoute('<current>')->toString(),
                ],
              ]),
            ],
          ],
        ],
      ];
    }

    $build['table']['#rows'] = $rows;

    return $build;
  }

}
