<?php

declare(strict_types=1);

namespace Drupal\flowdrop_runtime;

use Drupal\Component\Utility\Html;
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\flowdrop_runtime\Entity\FlowDropWorkflowSnapshotInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * List builder for FlowDrop Workflow Snapshot entities.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class FlowDropWorkflowSnapshotListBuilder extends EntityListBuilder {

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

  /**
   * Constructs a new FlowDropWorkflowSnapshotListBuilder.
   *
   * @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 {
    $header = [
      'id' => $this->t('ID'),
      'workflow_id' => $this->t('Workflow'),
      'status' => $this->t('Status'),
      'thread_id' => $this->t('Thread'),
      'nodes' => $this->t('Nodes'),
      'created' => $this->t('Created'),
      'changed' => $this->t('Updated'),
    ];
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity): array {
    if (!$entity instanceof FlowDropWorkflowSnapshotInterface) {
      return parent::buildRow($entity);
    }

    // Count node states.
    $nodeStates = $entity->getNodeStates();
    $completed = 0;
    $total = count($nodeStates);
    foreach ($nodeStates as $nodeState) {
      if (($nodeState['status'] ?? '') === 'completed') {
        $completed++;
      }
    }

    // Status badge color.
    $status = $entity->getSnapshotStatus();
    $statusClass = match ($status) {
      'completed' => 'color-success',
      'failed' => 'color-error',
      'running' => 'color-warning',
      'paused', 'approval_required' => 'color-warning',
      default => '',
    };

    $row = [
      'id' => $entity->id(),
      'workflow_id' => $entity->getWorkflowId(),
      'status' => [
        'data' => [
          '#markup' => '<span class="' . $statusClass . '">' . Html::escape(ucfirst($status)) . '</span>',
        ],
      ],
      'thread_id' => $entity->getThreadId() ?: '-',
      'nodes' => $this->t('@completed/@total completed', [
        '@completed' => $completed,
        '@total' => $total,
      ]),
      'created' => $this->dateFormatter->format(
        (int) $entity->get('created')->value,
        'short',
      ),
      'changed' => $this->dateFormatter->format(
        (int) $entity->getChangedTime(),
        'short',
      ),
    ];

    return $row + parent::buildRow($entity);
  }

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

    // Add view operation.
    $operations['view'] = [
      'title' => $this->t('View'),
      'weight' => -10,
      'url' => $entity->toUrl('canonical'),
    ];

    return $operations;
  }

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

    // Add summary information.
    $build['summary'] = [
      '#type' => 'container',
      '#attributes' => ['class' => ['snapshot-summary']],
      '#weight' => -10,
    ];

    // Count snapshots by status.
    $query = $this->getStorage()->getQuery()
      // Access bypassed: admin list builder; route permission controls access.
      ->accessCheck(FALSE);
    $total = $query->count()->execute();

    $build['summary']['total'] = [
      '#markup' => '<p>' . $this->t('Total snapshots: @count', ['@count' => $total]) . '</p>',
    ];

    // Add cleanup link.
    $build['actions'] = [
      '#type' => 'container',
      '#attributes' => ['class' => ['snapshot-actions']],
      '#weight' => -5,
    ];

    $build['actions']['cleanup'] = [
      '#type' => 'link',
      '#title' => $this->t('Cleanup old snapshots'),
      '#url' => Url::fromRoute('flowdrop_runtime.snapshot_cleanup'),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEntityIds(): array {
    $query = $this->getStorage()->getQuery()
      // Access bypassed: admin list builder; route permission controls access.
      ->accessCheck(FALSE)
      ->sort('created', 'DESC')
      ->pager(50);

    return $query->execute();
  }

}
