<?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\Form\FormBuilderInterface;
use Drupal\Core\Url;
use Drupal\flowdrop_orchestration\DTO\Snapshot\NodeSnapshot;
use Drupal\flowdrop_orchestration\DTO\Snapshot\WorkflowSnapshot;
use Drupal\flowdrop_runtime\Entity\FlowDropWorkflowSnapshotInterface;
use Drupal\flowdrop_runtime\Form\WorkflowSnapshotFilterForm;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * 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;

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

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected RequestStack $requestStack;

  /**
   * 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 {
    $instance = new static(
      $entity_type,
      $container->get('entity_type.manager')->getStorage($entity_type->id()),
      $container->get('date.formatter'),
    );
    $instance->formBuilder = $container->get('form_builder');
    $instance->requestStack = $container->get('request_stack');
    return $instance;
  }

  /**
   * {@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'] ?? '') === NodeSnapshot::STATUS_COMPLETED) {
        $completed++;
      }
    }

    // Status badge color.
    $status = $entity->getSnapshotStatus();
    $statusClass = match ($status) {
      WorkflowSnapshot::STATUS_COMPLETED => 'color-success',
      WorkflowSnapshot::STATUS_FAILED => 'color-error',
      WorkflowSnapshot::STATUS_RUNNING => 'color-warning',
      WorkflowSnapshot::STATUS_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();

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

    // 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 {
    $request = $this->requestStack->getCurrentRequest();
    $query = $this->getStorage()->getQuery()
      // Access bypassed: admin list builder; route permission controls access.
      ->accessCheck(FALSE);

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

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

    $query->sort('created', 'DESC')->pager(50);

    return $query->execute();
  }

}
