<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow;

use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityAccessControlHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Pager\PagerManagerInterface;
use Drupal\Core\Url;
use Drupal\flowdrop_workflow\Form\WorkflowFilterForm;
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.
   * @param \Drupal\Core\Form\FormBuilderInterface $formBuilder
   *   The form builder.
   * @param \Drupal\Core\Entity\EntityAccessControlHandlerInterface $accessHandler
   *   The workflow access control handler, used for create access checks.
   */
  public function __construct(
    EntityTypeInterface $entity_type,
    EntityStorageInterface $storage,
    protected readonly PagerManagerInterface $pagerManager,
    protected readonly RequestStack $requestStack,
    ModuleHandlerInterface $moduleHandler,
    protected readonly FormBuilderInterface $formBuilder,
    protected readonly EntityAccessControlHandlerInterface $accessHandler,
  ) {
    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'),
      $container->get('form_builder'),
      $entity_type_manager->getAccessControlHandler($entity_type->id()),
    );
  }

  /**
   * {@inheritdoc}
   *
   * Loads the full result set with no query pager so that filtering, 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 filtering/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();

    // Apply filters from URL query parameters.
    $request = $this->requestStack->getCurrentRequest();
    $statusFilter = $request->query->get('status', '');
    if ($statusFilter === 'enabled') {
      $entities = array_filter($entities, function ($e): bool {
        /** @var \Drupal\flowdrop_workflow\FlowDropWorkflowInterface $e */
        return (bool) $e->status();
      });
    }
    elseif ($statusFilter === 'disabled') {
      $entities = array_filter($entities, function ($e): bool {
        /** @var \Drupal\flowdrop_workflow\FlowDropWorkflowInterface $e */
        return !$e->status();
      });
    }

    // Get sort parameters from request.
    $order = $request->query->get("order");
    $sort = in_array($request->query->get("sort"), ['asc', 'desc'], TRUE)
      ? $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";

    $build["filter_form"] = $this->formBuilder->getForm(WorkflowFilterForm::class);
    $build["filter_form"]["#weight"] = -10;

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

    // Clarify the default entity edit link: it opens the settings form, as
    // opposed to the visual "FlowDrop Editor" canvas.
    if (isset($operations['edit'])) {
      $operations['edit']['title'] = $this->t('Edit Settings');
    }

    // Add Editor link. The visual editor is an edit surface, so it follows
    // update access like the parent-provided edit operation.
    if ($entity->access('update')) {
      $operations['editor'] = [
        'title' => $this->t('FlowDrop Editor'),
        'weight' => -10,
        'url' => Url::fromRoute('flowdrop.workflow.editor', [
          'flowdrop_workflow' => $entity->id(),
        ]),
      ];
    }

    // Add Duplicate link, after Edit Settings (10) and before Delete (100).
    // Duplicating reads the source graph and creates a new workflow, so it
    // mirrors the duplicate route's view + create requirement.
    if ($entity->access('view') && $this->accessHandler->createAccess()) {
      $operations['duplicate'] = [
        'title' => $this->t('Duplicate'),
        'weight' => 15,
        'url' => Url::fromRoute('flowdrop.workflow.duplicate', [
          'flowdrop_workflow' => $entity->id(),
        ]),
      ];
    }

    // Add Doctor link. The doctor diagnoses and repairs the stored workflow,
    // so it follows update access like the editor and the settings form.
    if ($entity->access('update')) {
      $operations['doctor'] = [
        'title' => $this->t('Doctor'),
        'weight' => 20,
        'url' => Url::fromRoute('flowdrop.workflow.doctor', [
          '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 Sessions'),
        'weight' => 5,
        'url' => Url::fromRoute('flowdrop_playground.workflow.sessions', [
          'flowdrop_workflow' => $entity->id(),
        ]),
      ];
    }

    return $operations;
  }

}
