<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_category;

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

/**
 * Provides a listing of flowdrop node categories.
 *
 * 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.
 */
final class FlowDropNodeCategoryListBuilder 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 FlowDropNodeCategoryListBuilder 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}
   *
   * Loads the full result set with no query pager so that sorting and
   * pagination can be applied in-memory in ::load(). The base implementation
   * applies a query pager whenever $limit is set, which would slice the
   * result to the first page before this list builder's custom logic runs —
   * breaking cross-page sorting and suppressing the pager (its total item
   * count would be capped at one page's worth).
   */
  protected function getEntityListQuery(): QueryInterface {
    return $this->getStorage()->getQuery()->accessCheck(TRUE);
  }

  /**
   * {@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",
        "Machine name" => "id",
        "Status" => "status",
      ];
      if (isset($fieldMap[$order])) {
        $this->sortField = $fieldMap[$order];
        $this->sortDirection = $sort;
      }
    }

    // Sort entities in memory.
    usort($entities, function ($a, $b) {
      /** @var \Drupal\flowdrop_node_category\FlowDropNodeCategoryInterface $a */
      /** @var \Drupal\flowdrop_node_category\FlowDropNodeCategoryInterface $b */
      $valueA = $this->getEntitySortValue($a, $this->sortField);
      $valueB = $this->getEntitySortValue($b, $this->sortField);

      // 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);
  }

  /**
   * Gets the value for sorting from an entity.
   *
   * @param \Drupal\flowdrop_node_category\FlowDropNodeCategoryInterface $entity
   *   The entity to get the value from.
   * @param string $field
   *   The field name to get.
   *
   * @return mixed
   *   The value for sorting.
   */
  protected function getEntitySortValue(FlowDropNodeCategoryInterface $entity, string $field): mixed {
    switch ($field) {
      case "label":
        return strtolower($entity->label() ?? "");

      case "id":
        return strtolower($entity->id() ?? "");

      case "status":
        return $entity->status() ? 1 : 0;

      default:
        return "";
    }
  }

  /**
   * {@inheritdoc}
   *
   * Consistent column order: Label, Status, Machine name.
   *
   * @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",
      ],
      "status" => [
        "data" => $this->t("Status"),
        "field" => "status",
        "specifier" => "status",
      ],
      "id" => [
        "data" => $this->t("Machine name"),
        "field" => "id",
        "specifier" => "id",
      ],
    ];
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   *
   * @return array<string, mixed>
   *   An array of row data for the entity.
   */
  public function buildRow(EntityInterface $entity): array {
    /** @var \Drupal\flowdrop_node_category\FlowDropNodeCategoryInterface $entity */
    $row["label"] = $entity->label();
    $row["status"] = $this->buildStatusPill($entity->status());
    $row["id"] = $entity->id();
    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";

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

    return $build;
  }

  /**
   * Builds a status pill render array for table cell display.
   *
   * @param bool $isEnabled
   *   Whether the entity is enabled.
   *
   * @return array<string, mixed>
   *   A table cell render array containing the status pill component.
   */
  private function buildStatusPill(bool $isEnabled): array {
    // Wrap component in 'data' key for proper table cell rendering.
    return [
      "data" => [
        "#type" => "component",
        "#component" => "flowdrop_ui_components:pill",
        "#props" => [
          "label" => $isEnabled ? (string) $this->t("Enabled") : (string) $this->t("Disabled"),
          "variant" => $isEnabled ? "success" : "neutral",
          "style" => "soft",
          "size" => "sm",
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultOperations(EntityInterface $entity): array {
    $operations = [];

    $entityId = $entity->id();
    if (is_string($entityId)) {
      // Edit operation.
      $operations["edit"] = [
        "title" => $this->t("Edit"),
        "url" => Url::fromRoute("entity.flowdrop_node_category.edit_form", [
          "flowdrop_node_category" => $entityId,
        ]),
        "weight" => 10,
      ];

      // Delete operation.
      $operations["delete"] = [
        "title" => $this->t("Delete"),
        "url" => Url::fromRoute("entity.flowdrop_node_category.delete_form", [
          "flowdrop_node_category" => $entityId,
        ]),
        "weight" => 100,
      ];
    }

    return $operations;
  }

}
