<?php

namespace Drupal\eb;

use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Url;
use Drupal\eb\Entity\EbRollbackInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * List builder for EbRollback entities.
 */
class EbRollbackListBuilder extends EntityListBuilder {

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected DateFormatterInterface $dateFormatter;

  /**
   * Constructs a new EbRollbackListBuilder object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   */
  public function __construct(
    EntityTypeInterface $entity_type,
    EntityStorageInterface $storage,
    DateFormatterInterface $date_formatter,
  ) {
    parent::__construct($entity_type, $storage);
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type): static {
    return new static(
      $entity_type,
      $container->get('entity_type.manager')->getStorage($entity_type->id()),
      $container->get('date.formatter'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildHeader(): array {
    return [
      'label' => $this->t('Label'),
      'definition_id' => $this->t('Definition'),
      'operation_count' => $this->t('Operations'),
      'status' => $this->t('Status'),
      'created' => $this->t('Created'),
    ] + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity): array {
    assert($entity instanceof EbRollbackInterface);

    $created = $entity->get('created')->value;

    return [
      'label' => $entity->label(),
      'definition_id' => $entity->getDefinitionId() ?: '-',
      'operation_count' => $entity->getOperationCount(),
      'status' => $this->buildStatusBadge($entity->getStatus()),
      'created' => $created ? $this->dateFormatter->format((int) $created, 'short') : '-',
    ] + parent::buildRow($entity);
  }

  /**
   * Builds a status badge render array.
   *
   * @param string $status
   *   The status string.
   *
   * @return array<string, mixed>
   *   A render array for the status badge.
   */
  protected function buildStatusBadge(string $status): array {
    $labels = [
      'pending' => $this->t('Pending'),
      'completed' => $this->t('Completed'),
      'failed' => $this->t('Failed'),
    ];
    $classes = [
      'pending' => 'admin-missing',
      'completed' => 'admin-enabled',
      'failed' => 'admin-required',
    ];

    return [
      '#markup' => '<span class="eb-status-badge ' . ($classes[$status] ?? '') . '">' . ($labels[$status] ?? $status) . '</span>',
    ];
  }

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

    assert($entity instanceof EbRollbackInterface);

    // Add rollback action for pending rollbacks only.
    if ($entity->isPending()) {
      $operations['rollback'] = [
        'title' => $this->t('Rollback'),
        'weight' => 10,
        'url' => Url::fromRoute('eb.rollback_execute', [
          'rollback_id' => $entity->id(),
        ]),
      ];
    }

    return $operations;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEntityIds(): array {
    $query = $this->getStorage()->getQuery()
      ->accessCheck(TRUE)
      ->sort('created', 'DESC');

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $query->pager($this->limit);
    }

    return $query->execute();
  }

}
