<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow;

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

/**
 * Provides a listing of FlowDropWorkflow entities.
 *
 * Features sortable table headers with default sorting by changed date
 * (newest first). Supports pagination for large datasets.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class FlowDropWorkflowListBuilder extends ConfigEntityListBuilder {

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

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

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

  /**
   * Constructs a new FlowDropWorkflowListBuilder 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.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
   *   The module handler service.
   */
  public function __construct(
    EntityTypeInterface $entity_type,
    EntityStorageInterface $storage,
    protected readonly PagerManagerInterface $pagerManager,
    protected readonly RequestStack $requestStack,
    ModuleHandlerInterface $moduleHandler,
  ) {
    parent::__construct($entity_type, $storage);
    $this->moduleHandler = $moduleHandler;
  }

  /**
   * {@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'),
      $container->get('module_handler'),
    );
  }

  /**
   * {@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", "desc");

    // Determine the field to sort by based on header label.
    if ($order !== NULL) {
      $fieldMap = [
        "Label" => "label",
        "Status" => "status",
        "Description" => "description",
        "Nodes" => "nodes",
        "Created" => "created",
        "Modified" => "changed",
      ];
      if (isset($fieldMap[$order])) {
        $this->sortField = $fieldMap[$order];
        $this->sortDirection = $sort;
      }
    }

    // Sort entities in memory.
    usort($entities, function ($a, $b) {
      /** @var \Drupal\flowdrop_workflow\Entity\FlowDropWorkflow $a */
      /** @var \Drupal\flowdrop_workflow\Entity\FlowDropWorkflow $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 the value for sorting from an entity.
   *
   * @param \Drupal\flowdrop_workflow\FlowDropWorkflowInterface $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(FlowDropWorkflowInterface $entity, string $field): mixed {
    switch ($field) {
      case "label":
        return strtolower($entity->label() ?? "");

      case "description":
        return strtolower($entity->getDescription());

      case "nodes":
        return count($entity->getNodes());

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

      case "created":
        return $entity->getCreated();

      case "changed":
        return $entity->getChanged();

      default:
        return "";
    }
  }

  /**
   * {@inheritdoc}
   *
   * Consistent column order: Label, Status, Description, Nodes, Created,
   * Modified.
   *
   * @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",
      ],
      "status" => [
        "data" => $this->t("Status"),
        "field" => "status",
        "specifier" => "status",
      ],
      "description" => [
        "data" => $this->t("Description"),
        "field" => "description",
        "specifier" => "description",
      ],
      "nodes" => [
        "data" => $this->t("Nodes"),
        "field" => "nodes",
        "specifier" => "nodes",
      ],
      "created" => [
        "data" => $this->t("Created"),
        "field" => "created",
        "specifier" => "created",
      ],
      "changed" => [
        "data" => $this->t("Modified"),
        "field" => "changed",
        "specifier" => "changed",
        "sort" => "desc",
      ],
    ];
    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_workflow\Entity\FlowDropWorkflow $entity */
    $row["label"] = $entity->label();
    $row["status"] = $this->buildStatusPill($entity->status());
    $row["description"] = $entity->getDescription() ?: $this->t("No description");
    $row["nodes"] = count($entity->getNodes());
    $row["created"] = $entity->getCreated() ? date("Y-m-d H:i:s", $entity->getCreated()) : $this->t("Unknown");
    $row["changed"] = $entity->getChanged() ? date("Y-m-d H:i:s", $entity->getChanged()) : $this->t("Unknown");
    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;
  }

  /**
   * {@inheritdoc}
   *
   * @return array<\Drupal\Core\Entity\EntityInterface>
   *   An array of 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);
  }

  /**
   * 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 {
    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}
   *
   * @return array<string, array<string, mixed>>
   *   An array of operation definitions.
   */
  public function getDefaultOperations(EntityInterface $entity): array {
    $operations = parent::getDefaultOperations($entity);

    // Add Editor link.
    $operations['editor'] = [
      'title' => $this->t('Editor'),
      'weight' => -10,
      'url' => Url::fromRoute('flowdrop.workflow.editor', [
        'flowdrop_workflow' => $entity->id(),
      ]),
    ];

    // Add Playground link (only if the playground module is enabled).
    if ($this->moduleHandler->moduleExists('flowdrop_playground')) {
      $operations['playground'] = [
        'title' => $this->t('Playground'),
        'weight' => 5,
        'url' => Url::fromRoute('flowdrop_playground.page', [
          'flowdrop_workflow' => $entity->id(),
        ]),
      ];
    }

    return $operations;
  }

}
