<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_type;

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

/**
 * Provides a listing of flowdrop node types.
 */
final class FlowDropNodeTypeListBuilder extends ConfigEntityListBuilder {

  /**
   * {@inheritdoc}
   */
  public function buildHeader(): array {
    $header["id"] = $this->t("ID");
    $header["label"] = $this->t("Label");
    $header["category"] = $this->t("Category");
    $header["plugin_version"] = $this->t("Plugin Version");
    $header["enabled"] = $this->t("Enabled");
    $header["executor_plugin"] = $this->t("Executor Plugin");
    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_node_type\FlowDropNodeTypeInterface $entity */
    $row["id"] = $entity->id();
    $row["label"] = $entity->label();
    $row["category"] = $this->t("@category", ["@category" => ucfirst($entity->getCategory())]);
    $row["plugin_version"] = $entity->getPluginVersion() ?: $this->t("N/A");
    $row["enabled"] = $this->buildStatusPill($entity->isEnabled());
    $row["executor_plugin"] = $entity->getExecutorPlugin() ?: $this->t("None");
    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("Yes") : (string) $this->t("No"),
          "variant" => $isEnabled ? "success" : "neutral",
          "style" => "soft",
          "size" => "sm",
        ],
      ],
    ];
  }

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

    // Edit operation.
    $entityId = $entity->id();
    if (is_string($entityId)) {
      $operations["edit"] = [
        "title" => $this->t("Edit"),
        "url" => $entity->toUrl("edit-form"),
        "weight" => 10,
      ];

      // Delete operation.
      $operations["delete"] = [
        "title" => $this->t("Delete"),
        "url" => $entity->toUrl("delete-form"),
        "weight" => 100,
      ];
    }

    return $operations;
  }

}
