<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow;

use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;

/**
 * Provides a listing of FlowDropWorkflow entities.
 */
class FlowDropWorkflowListBuilder extends ConfigEntityListBuilder {

  /**
   * {@inheritdoc}
   *
   * @return array<string, mixed>
   *   An array of header definitions.
   */
  public function buildHeader(): array {
    $header["label"] = $this->t("Workflow");
    $header["description"] = $this->t("Description");
    $header["nodes"] = $this->t("Nodes");
    $header["status"] = $this->t("Status");
    $header["created"] = $this->t("Created");
    $header["changed"] = $this->t("Modified");
    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_workflow\Entity\FlowDropWorkflow $entity */
    $row["label"] = $entity->label();
    $row["description"] = $entity->getDescription() ?: $this->t("No description");
    $row["nodes"] = count($entity->getNodes());
    $row["status"] = $this->buildStatusPill($entity->status());
    $row["created"] = $entity->getCreated() ? date("Y-m-d H:i:s", $entity->getCreated()) : $this->t("Unknown");
    $row["changed"] = $entity->getChanged() ? date("Y-m-d H:i:s", $entity->getChanged()) : $this->t("Unknown");
    return $row + parent::buildRow($entity);
  }

  /**
   * Builds a status pill render array for table cell display.
   *
   * @param bool $isEnabled
   *   Whether the entity is enabled.
   *
   * @return array<string, mixed>
   *   A table cell render array containing the status pill component.
   */
  private function buildStatusPill(bool $isEnabled): array {
    return [
      "data" => [
        "#type" => "component",
        "#component" => "flowdrop_ui_components:pill",
        "#props" => [
          "label" => $isEnabled ? (string) $this->t("Enabled") : (string) $this->t("Disabled"),
          "variant" => $isEnabled ? "success" : "neutral",
          "style" => "soft",
          "size" => "sm",
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   *
   * @return array<string, array<string, mixed>>
   *   An array of operation definitions.
   */
  public function getDefaultOperations(EntityInterface $entity): array {
    $operations = parent::getDefaultOperations($entity);

    return $operations;
  }

}
