<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_category;

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

/**
 * Provides a listing of flowdrop node categories.
 */
final class FlowDropNodeCategoryListBuilder extends ConfigEntityListBuilder {

  /**
   * {@inheritdoc}
   */
  public function buildHeader(): array {
    $header["label"] = $this->t("Label");
    $header["id"] = $this->t("Machine name");
    $header["status"] = $this->t("Status");
    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_category\FlowDropNodeCategoryInterface $entity */
    $row["label"] = $entity->label();
    $row["id"] = $entity->id();
    $row["status"] = $this->buildStatusPill($entity->status());
    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 {
    // Wrap component in 'data' key for proper table cell rendering.
    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}
   */
  public function getDefaultOperations(EntityInterface $entity): array {
    $operations = [];

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

      // Delete operation.
      $operations["delete"] = [
        "title" => $this->t("Delete"),
        "url" => Url::fromRoute("entity.flowdrop_node_category.delete_form", [
          "flowdrop_node_category" => $entityId,
        ]),
        "weight" => 100,
      ];
    }

    return $operations;
  }

}
