<?php

namespace Drupal\component_builder\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
use Drupal\Core\Url;
use Drupal\Core\Form\FormStateInterface;

/**
 * Default implementation of the Entity Reference Selection for Component.
 *
 * @EntityReferenceSelection(
 *   id = "default:component_wrapper",
 *   label = @Translation("Component"),
 *   group = "default",
 *   entity_types = {"component_wrapper"},
 * )
 */
class ComponentSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $configuration = $this->getConfiguration();
    $bundles = $this->entityTypeBundleInfo->getBundleInfo('component_item');
    $bundle_options = [];

    foreach ($bundles as $bundle_name => $bundle_info) {
      $bundle_options[$bundle_name] = $bundle_info['label'];
    }

    $form['target_bundles'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Component Types'),
      '#options' => $bundle_options,
      '#default_value' => $configuration['target_bundles'] ?? [],
    ];

    if (empty($bundle_options)) {
      $form['allowed_bundles_explain'] = [
        '#type' => 'markup',
        '#markup' => $this->t('You did not add any Component Item types yet, click <a href=":here">here</a> to add one.', [
          ':here' => Url::fromRoute('entity.component_item_type.add_form')->toString(),
        ]),
      ];
    }

    return $form;
  }

}
