<?php

declare(strict_types=1);

namespace Drupal\flowdrop_job;

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\flowdrop\ListBuilder\FlowDropListBuilderTrait;
use Drupal\flowdrop_job\Form\JobFilterForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

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

  use FlowDropListBuilderTrait;

  /**
   * The node type entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected EntityStorageInterface $nodeTypeStorage;

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

  /**
   * {@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->nodeTypeStorage = $container->get("entity_type.manager")
      ->getStorage("flowdrop_node_type");
    $instance->requestStack = $container->get("request_stack");
    $instance->formBuilder = $container->get("form_builder");
    return $instance;
  }

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

  /**
   * {@inheritdoc}
   *
   * Consistent column order: Label, Status, Node Type, Priority, 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",
      ],
      "node_type" => [
        "data" => $this->t("Node Type"),
        "field" => "node_type_id",
        "specifier" => "node_type_id",
      ],
      "priority" => [
        "data" => $this->t("Priority"),
        "field" => "priority",
        "specifier" => "priority",
      ],
      "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}
   *
   * @return array<string, mixed>
   *   An array of row data for the entity.
   */
  public function buildRow(EntityInterface $entity): array {
    /** @var \Drupal\flowdrop_job\FlowDropJobInterface $entity */
    $row["label"] = $entity->toLink();
    $row["status"] = $this->buildExecutionStatusPill($entity->getStatus());
    $row["node_type"] = $this->getNodeTypeLabel($entity->get("node_type_id")->target_id ?? "");
    $row["priority"] = $entity->getPriority();
    $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}
   */
  protected function getEntityIds(): array {
    $request = $this->requestStack->getCurrentRequest();
    $query = $this->getStorage()->getQuery()
      ->accessCheck(TRUE);

    $status = $request->query->get('status', '');
    $nodeType = $request->query->get('node_type', '');
    $dateFrom = $request->query->get('date_from', '');
    $dateTo = $request->query->get('date_to', '');

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

    $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');
    }

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

    return $query->execute();
  }

  /**
   * {@inheritdoc}
   */
  public function render(): array {
    $build = parent::render();

    $build['table']['#header'] = $this->buildHeader();
    $build['table']['#attributes']['class'][] = 'sortable-table';

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

    return $build;
  }

  /**
   * Gets the node type label with link.
   *
   * @param string $nodeTypeId
   *   The node type ID.
   *
   * @return array<string, mixed>
   *   Render array for node type label.
   */
  protected function getNodeTypeLabel(string $nodeTypeId): array {
    return $this->buildEntityReferenceLabel(
      $nodeTypeId,
      $this->nodeTypeStorage,
      "entity.flowdrop_node_type.edit_form",
      "flowdrop_node_type",
    );
  }

}
