<?php

namespace Drupal\eb\ListBuilder;

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\EbLogInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * List builder for EbLog entities.
 */
class EbLogListBuilder extends EntityListBuilder {

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

  /**
   * Constructs a new EbLogListBuilder 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 {
    // @phpstan-ignore new.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'),
      'action' => $this->t('Action'),
      'operations_count' => $this->t('Operations'),
      'status' => $this->t('Status'),
      'created' => $this->t('Date'),
      'rollback' => $this->t('Rollback'),
    ] + parent::buildHeader();
  }

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

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

    $rollback_link = '-';
    if ($rollback_id !== NULL) {
      $rollback_link = [
        'data' => [
          '#type' => 'link',
          '#title' => $this->t('View'),
          '#url' => Url::fromRoute('entity.eb_rollback.canonical', [
            'eb_rollback' => $rollback_id,
          ]),
        ],
      ];
    }

    return [
      'label' => $entity->label(),
      'action' => $entity->getAction(),
      'operations_count' => $this->t('@success/@total', [
        '@success' => $entity->getSuccessCount(),
        '@total' => $entity->getOperationCount(),
      ]),
      'status' => [
        'data' => $this->buildStatusBadge($entity->getStatus()),
      ],
      'created' => $created ? $this->dateFormatter->format((int) $created, 'short') : '-',
      'rollback' => $rollback_link,
    ] + 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'),
      'success' => $this->t('Success'),
      'partial' => $this->t('Partial'),
      'failed' => $this->t('Failed'),
    ];
    $classes = [
      'pending' => 'admin-missing',
      'success' => 'admin-enabled',
      'partial' => 'admin-required',
      '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 EbLogInterface);

    // Add "Show" operation to view watchdog logs.
    $operations['show'] = [
      'title' => $this->t('Show'),
      'weight' => 10,
      'url' => Url::fromRoute('eb.eb_log.show', [
        'eb_log' => $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();
  }

}
