<?php

declare(strict_types=1);

namespace Drupal\flowdrop_job;

use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Pager\PagerManagerInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Defines a class to build a listing of flowdrop job type entities.
 *
 * Features sortable table headers with default sorting by label alphabetically.
 * Supports pagination for large datasets.
 *
 * @internal This class is not part of the public API and may change without notice.
 *
 * @see \Drupal\flowdrop_job\Entity\FlowDropJobType
 */
final class FlowDropJobTypeListBuilder extends ConfigEntityListBuilder {

  /**
   * The number of entities to list per page.
   *
   * @var int
   */
  protected $limit = 50;

  /**
   * The current sort field.
   *
   * @var string
   */
  protected string $sortField = "label";

  /**
   * The current sort direction.
   *
   * @var string
   */
  protected string $sortDirection = "asc";

  /**
   * Constructs a new FlowDropJobTypeListBuilder object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage class.
   * @param \Drupal\Core\Pager\PagerManagerInterface $pagerManager
   *   The pager manager service.
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   */
  public function __construct(
    EntityTypeInterface $entity_type,
    EntityStorageInterface $storage,
    protected readonly PagerManagerInterface $pagerManager,
    protected readonly RequestStack $requestStack,
  ) {
    parent::__construct($entity_type, $storage);
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type): static {
    $entity_type_manager = $container->get('entity_type.manager');
    return new static(
      $entity_type,
      $entity_type_manager->getStorage($entity_type->id()),
      $container->get('pager.manager'),
      $container->get('request_stack'),
    );
  }

  /**
   * {@inheritdoc}
   *
   * @return array<\Drupal\Core\Entity\EntityInterface>
   *   An array of entities sorted according to the current tablesort.
   */
  public function load(): array {
    $entities = parent::load();

    // Get sort parameters from request.
    $request = $this->requestStack->getCurrentRequest();
    $order = $request->query->get("order");
    $sort = $request->query->get("sort", "asc");

    // Determine the field to sort by based on header label.
    if ($order !== NULL) {
      $fieldMap = [
        "Label" => "label",
      ];
      if (isset($fieldMap[$order])) {
        $this->sortField = $fieldMap[$order];
        $this->sortDirection = in_array($sort, ['asc', 'desc'], TRUE) ? $sort : 'asc';
      }
    }

    // Sort entities in memory.
    usort($entities, function ($a, $b) {
      /** @var \Drupal\Core\Entity\EntityInterface $a */
      /** @var \Drupal\Core\Entity\EntityInterface $b */
      $valueA = strtolower($a->label() ?? "");
      $valueB = strtolower($b->label() ?? "");

      // Compare values.
      if ($valueA === $valueB) {
        return 0;
      }

      $result = $valueA < $valueB ? -1 : 1;

      // Reverse for descending order.
      if ($this->sortDirection === "desc") {
        $result = -$result;
      }

      return $result;
    });

    // Apply pagination.
    return $this->getEntityListForPager($entities);
  }

  /**
   * Gets a paginated slice of entities.
   *
   * @param array<\Drupal\Core\Entity\EntityInterface> $entities
   *   All sorted entities.
   *
   * @return array<\Drupal\Core\Entity\EntityInterface>
   *   Entities for the current page.
   */
  protected function getEntityListForPager(array $entities): array {
    // Get current page from request.
    $page = $this->requestStack->getCurrentRequest()?->query->getInt("page", 0) ?? 0;

    // Calculate offset.
    $offset = $page * $this->limit;

    // Initialize pager.
    $this->pagerManager->createPager(count($entities), $this->limit);

    // Return slice of entities for current page.
    return array_slice($entities, $offset, $this->limit);
  }

  /**
   * {@inheritdoc}
   *
   * @return array<string, array<string, mixed>>
   *   An array of sortable header definitions.
   */
  public function buildHeader(): array {
    $header = [
      "label" => [
        "data" => $this->t("Label"),
        "field" => "label",
        "specifier" => "label",
        "sort" => "asc",
      ],
    ];
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity): array {
    $row["label"] = $entity->label();
    return $row + parent::buildRow($entity);
  }

  /**
   * {@inheritdoc}
   *
   * @return array<string, mixed>
   *   The render array for the list.
   */
  public function render(): array {
    $build = parent::render();

    // Add tablesort to the table.
    $build["table"]["#header"] = $this->buildHeader();
    $build["table"]["#attributes"]["class"][] = "sortable-table";
    $build["table"]["#empty"] = $this->t(
      'No flowdrop job types available. <a href=":link">Add flowdrop job type</a>.',
      [":link" => Url::fromRoute("flowdrop.structure.job_type.add")->toString()],
    );

    // Add pager for pagination.
    $build["pager"] = [
      "#type" => "pager",
    ];

    return $build;
  }

}
