<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\Form\Trait;

use Drupal\Core\Url;
use Drupal\flowdrop_trigger\Enum\EventCategory;
use Drupal\flowdrop_trigger\FlowDropTriggerConfigInterface;

/**
 * Provides restriction warning logic for the trigger config form.
 *
 * Checks trigger configuration against site-wide restrictions and
 * displays warning messages when the trigger may not fire.
 *
 * Requirements for using this trait:
 * - The class must use TriggerFormOptionsTrait (for label methods)
 * - The class must have an $eventTypeManager property
 *   of type EventTypePluginManager
 * - The class must have a $configFactory property or configFactory() method
 * - The class must implement t() for translation
 *
 * @internal This trait is not part of the public API and may change without notice.
 */
trait TriggerRestrictionWarningsTrait {

  /**
   * Add warning messages for restricted event types, entity types, or bundles.
   *
   * Checks the trigger's configuration against site-wide restrictions and
   * displays warning messages if the trigger will not fire due to restrictions.
   *
   * @param \Drupal\flowdrop_trigger\FlowDropTriggerConfigInterface $entity
   *   The trigger configuration entity.
   * @param array<string, mixed> &$form
   *   The form array to add warning elements to.
   */
  protected function addRestrictionWarnings(FlowDropTriggerConfigInterface $entity, array &$form): void {
    // Only show warnings for existing entities with configuration.
    if ($entity->isNew()) {
      return;
    }

    $eventType = $entity->getEventType();
    if (empty($eventType)) {
      return;
    }

    // Get event type definition to determine category.
    $definition = $this->eventTypeManager->getDefinition($eventType, FALSE);
    if (!$definition) {
      return;
    }

    $category = EventCategory::toString($definition["category"] ?? "entity");
    $configName = sprintf("flowdrop_trigger.settings.%s", $category);
    $config = $this->configFactory->get($configName);

    $warnings = [];

    // Determine settings URL based on category.
    $settingsRouteMap = [
      "entity" => "flowdrop.config.triggers.entity",
      "form" => "flowdrop.config.triggers.form",
      "user" => "flowdrop.config.triggers.user",
    ];
    $settingsRoute = $settingsRouteMap[$category] ?? "flowdrop.config.triggers";
    $settingsUrl = Url::fromRoute($settingsRoute)->toString();

    // Check if category is enabled.
    if (!($config->get("enabled") ?? TRUE)) {
      $categoryLabel = ucfirst($category);
      $warnings[] = $this->t(
        'The <strong>@category</strong> event category is disabled in the <a href="@settings_url">trigger settings</a>. This trigger will not fire until the category is enabled.',
        [
          "@category" => $categoryLabel,
          "@settings_url" => $settingsUrl,
        ]
      );
    }

    // Check event type restriction.
    $allowedEventTypes = $config->get("allowed_event_types") ?? [];
    if (!empty($allowedEventTypes)) {
      if (!in_array($eventType, $allowedEventTypes, TRUE)) {
        $eventTypeLabel = $this->getEventTypeLabel($eventType);
        $warnings[] = $this->t(
          'The event type "<strong>@event_type</strong>" is not enabled in the <a href="@settings_url">@category trigger settings</a>. This trigger will not fire until the event type is enabled.',
          [
            "@event_type" => $eventTypeLabel,
            "@settings_url" => $settingsUrl,
            "@category" => ucfirst($category),
          ]
        );
      }
    }

    // Check entity-specific restrictions (only for entity events).
    if ($category === "entity") {
      $conditions = $entity->getConditions();
      $triggerEntityTypes = $conditions["entity_types"] ?? [];
      $allowedEntityTypes = $config->get("allowed_entity_types") ?? [];

      if (!empty($allowedEntityTypes) && !empty($triggerEntityTypes)) {
        $disabledEntityTypes = array_diff($triggerEntityTypes, $allowedEntityTypes);
        if (!empty($disabledEntityTypes)) {
          $entityTypeLabels = array_map(
            fn($type) => $this->getEntityTypeLabel($type),
            $disabledEntityTypes
          );
          $warnings[] = $this->t(
            'The following entity types are not enabled in the <a href="@settings_url">entity trigger settings</a>: <strong>@entity_types</strong>. Events for these entity types will not trigger this workflow.',
            [
              "@entity_types" => implode(", ", $entityTypeLabels),
              "@settings_url" => $settingsUrl,
            ]
          );
        }
      }

      // Check bundle restrictions.
      $triggerBundles = $conditions["bundles"] ?? [];
      $allowedBundles = $config->get("allowed_bundles") ?? [];

      if (!empty($allowedBundles) && !empty($triggerBundles) && !empty($triggerEntityTypes)) {
        // Build the list of bundle keys this trigger uses.
        $triggerBundleKeys = [];
        foreach ($triggerEntityTypes as $entityTypeId) {
          foreach ($triggerBundles as $bundle) {
            $triggerBundleKeys[] = sprintf("%s:%s", $entityTypeId, $bundle);
          }
        }

        $disabledBundles = array_diff($triggerBundleKeys, $allowedBundles);
        if (!empty($disabledBundles)) {
          $warnings[] = $this->t(
            'The following bundles are not enabled in the <a href="@settings_url">entity trigger settings</a>: <strong>@bundles</strong>. Events for these bundles will not trigger this workflow.',
            [
              "@bundles" => implode(", ", $disabledBundles),
              "@settings_url" => $settingsUrl,
            ]
          );
        }
      }
    }

    // Display warnings if any.
    if (!empty($warnings)) {
      $form["restriction_warnings"] = [
        "#type" => "container",
        "#weight" => -100,
        "#attributes" => [
          "class" => ["messages", "messages--warning"],
        ],
      ];

      $form["restriction_warnings"]["title"] = [
        "#type" => "html_tag",
        "#tag" => "h3",
        "#value" => $this->t("⚠️ Trigger Restrictions Active"),
        "#attributes" => [
          "style" => "margin-top: 0;",
        ],
      ];

      $form["restriction_warnings"]["description"] = [
        "#type" => "html_tag",
        "#tag" => "p",
        "#value" => $this->t("This trigger may not fire due to site-wide restrictions configured by the administrator:"),
      ];

      $items = [];
      foreach ($warnings as $warning) {
        $items[] = ["#markup" => $warning];
      }

      $form["restriction_warnings"]["list"] = [
        "#theme" => "item_list",
        "#items" => $items,
      ];
    }
  }

}
