<?php

declare(strict_types=1);

namespace Drupal\flowdrop_pipeline;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\flowdrop\ListBuilder\FlowDropListBuilderTrait;
use Drupal\flowdrop_pipeline\Constants\PipelineStatus;
use Drupal\flowdrop_pipeline\Form\PipelineFilterForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a list controller for the flowdrop pipeline entity type.
 *
 * Features sortable table headers with default sorting by changed date
 * (newest first). Displays workflow reference and execution status.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class FlowDropPipelineListBuilder extends EntityListBuilder {

  use FlowDropListBuilderTrait;

  /**
   * The workflow entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected EntityStorageInterface $workflowStorage;

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected FormBuilderInterface $formBuilder;

  /**
   * Workflow id to scope the list to, or NULL for the global (all) list.
   *
   * When set, the list is filtered to this workflow and the Workflow column
   * and filter are hidden (they would be redundant).
   *
   * @var string|null
   */
  protected ?string $contextWorkflowId = NULL;

  /**
   * Scopes the list to a single workflow.
   *
   * @param string $workflow_id
   *   The workflow id.
   *
   * @return $this
   */
  public function setContextWorkflowId(string $workflow_id): static {
    $this->contextWorkflowId = $workflow_id;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(
    ContainerInterface $container,
    EntityTypeInterface $entity_type,
  ): static {
    $instance = new static(
      $entity_type,
      $container->get("entity_type.manager")->getStorage($entity_type->id()),
    );
    $instance->workflowStorage = $container->get("entity_type.manager")
      ->getStorage("flowdrop_workflow");
    $instance->requestStack = $container->get("request_stack");
    $instance->formBuilder = $container->get("form_builder");
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  protected function getSortableFields(): array {
    return ["id", "label", "status", "workflow_id", "created", "changed"];
  }

  /**
   * {@inheritdoc}
   *
   * Consistent column order: Label, Status, Workflow, Author, Created, Updated.
   *
   * @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",
      ],
    ];

    // The Workflow column is redundant when the list is scoped to one workflow.
    if ($this->contextWorkflowId === NULL) {
      $header["workflow"] = [
        "data" => $this->t("Workflow"),
        "field" => "workflow_id",
        "specifier" => "workflow_id",
      ];
    }

    $header += [
      "uid" => ["data" => $this->t("Author")],
      "created" => [
        "data" => $this->t("Created"),
        "field" => "created",
        "specifier" => "created",
      ],
      "changed" => [
        "data" => $this->t("Updated"),
        "field" => "changed",
        "specifier" => "changed",
        "sort" => "desc",
      ],
    ];
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   *
   * Adds a Re-run operation for pipelines in a terminal state.
   *
   * @return array<string, mixed>
   *   Operation links keyed by operation name.
   */
  public function getDefaultOperations(EntityInterface $entity): array {
    $operations = parent::getDefaultOperations($entity);

    /** @var \Drupal\flowdrop_pipeline\Entity\FlowDropPipelineInterface $entity */
    $terminalStatuses = [
      PipelineStatus::COMPLETED,
      PipelineStatus::FAILED,
      PipelineStatus::CANCELLED,
    ];

    if (in_array($entity->getStatus(), $terminalStatuses, TRUE) && $entity->access('update')) {
      $operations['rerun'] = [
        'title' => $this->t('Re-run'),
        'url' => Url::fromRoute('flowdrop.pipeline.rerun', [
          'flowdrop_pipeline' => $entity->id(),
        ]),
        'weight' => 10,
      ];
    }

    return $operations;
  }

  /**
   * {@inheritdoc}
   *
   * @return array<string, mixed>
   *   An array of row data for the entity.
   */
  public function buildRow(EntityInterface $entity): array {
    /** @var \Drupal\flowdrop_pipeline\Entity\FlowDropPipelineInterface $entity */
    $row["label"] = $entity->toLink();
    $row["status"] = $this->buildExecutionStatusPill($entity->getStatus());
    if ($this->contextWorkflowId === NULL) {
      $row["workflow"] = $this->getWorkflowLabel($entity->getWorkflowId());
    }
    $usernameOptions = [
      "label" => "hidden",
    ];
    $row["uid"]["data"] = $entity->get("uid")->view($usernameOptions);
    $row["created"]["data"] = $entity->get("created")->view(["label" => "hidden"]);
    $row["changed"]["data"] = $entity->get("changed")->view(["label" => "hidden"]);
    return $row + parent::buildRow($entity);
  }

  /**
   * {@inheritdoc}
   *
   * Extends the trait's sort logic with filter conditions from URL params.
   *
   * @return array<int|string>
   *   An array of filtered and sorted entity IDs.
   */
  protected function getEntityIds(): array {
    $request = $this->requestStack->getCurrentRequest();
    $query = $this->getStorage()->getQuery()
      ->accessCheck(TRUE);

    // Apply filters from URL query parameters. A scoped list always filters by
    // its context workflow and ignores the workflow query param.
    $workflow = $this->contextWorkflowId ?? $request->query->get('workflow', '');
    $status = $request->query->get('status', '');
    $dateFrom = $request->query->get('date_from', '');
    $dateTo = $request->query->get('date_to', '');

    if (!empty($workflow)) {
      $query->condition('workflow_id', $workflow);
    }
    if (!empty($status)) {
      $query->condition('status', $status);
    }
    if (!empty($dateFrom)) {
      $query->condition('created', strtotime($dateFrom), '>=');
    }
    if (!empty($dateTo)) {
      $query->condition('created', strtotime($dateTo . ' 23:59:59'), '<=');
    }

    // Apply tablesort — replicates FlowDropListBuilderTrait::getEntityIds().
    $header = $this->buildHeader();
    if (!empty($header)) {
      $order = $request->query->get('order');
      $sort = $request->query->get('sort', 'desc');

      $sortField = 'changed';
      if ($order !== NULL) {
        foreach ($header as $value) {
          if (is_array($value) && isset($value['data'])) {
            $headerLabel = $value['data'];
            if ($headerLabel instanceof TranslatableMarkup) {
              $headerLabel = $headerLabel->__toString();
            }
            if ($headerLabel === $order && isset($value['field'])) {
              $sortField = $value['field'];
              break;
            }
          }
        }
      }

      $sortableFields = $this->getSortableFields();
      if (in_array($sortField, $sortableFields, TRUE)) {
        $sortDirection = in_array(strtoupper($sort), ['ASC', 'DESC'], TRUE) ? strtoupper($sort) : 'DESC';
        $query->sort($sortField, $sortDirection);
      }
      else {
        $query->sort('changed', 'DESC');
      }
    }
    else {
      $query->sort('changed', 'DESC');
    }

    // Deterministic tiebreaker: when the primary sort values are equal (e.g.
    // pipelines updated within the same second), list the most recently
    // created first so "latest updated first" holds.
    $query->sort('id', 'DESC');

    if ($this->limit) {
      $query->pager($this->limit);
    }

    return $query->execute();
  }

  /**
   * {@inheritdoc}
   *
   * Prepends the filter form and replicates the trait's tablesort additions.
   *
   * @return array<string, mixed>
   *   The render array for the list with filter form and sortable headers.
   */
  public function render(): array {
    $build = parent::render();

    // Replicate FlowDropListBuilderTrait::render() additions.
    $build['table']['#header'] = $this->buildHeader();
    $build['table']['#attributes']['class'][] = 'sortable-table';

    // Prepend the filter form above the table. In a workflow-scoped list the
    // Workflow filter is hidden (it's fixed by the route).
    $build['filter_form'] = $this->formBuilder->getForm(
      PipelineFilterForm::class,
      $this->contextWorkflowId !== NULL,
    );
    $build['filter_form']['#weight'] = -10;

    return $build;
  }

  /**
   * Gets the workflow label with link.
   *
   * @param string $workflowId
   *   The workflow ID.
   *
   * @return array<string, mixed>
   *   Render array for workflow label.
   */
  protected function getWorkflowLabel(string $workflowId): array {
    return $this->buildEntityReferenceLabel(
      $workflowId,
      $this->workflowStorage,
      "entity.flowdrop_workflow.edit_form",
      "flowdrop_workflow",
    );
  }

}
