<?php

namespace Drupal\nodehive_content\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configuration form for NodeHive Content settings.
 */
class NodehiveContentSettingsForm extends ConfigFormBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * Constructs a NodehiveContentSettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    EntityTypeManagerInterface $entity_type_manager,
    EntityFieldManagerInterface $entity_field_manager,
  ) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('entity_type.manager'),
      $container->get('entity_field.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'nodehive_content_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['nodehive_content.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('nodehive_content.settings');
    $teaser_image_fields = $config->get('teaser_image_fields') ?? [];

    $form['teaser_image_fields'] = [
      '#type' => 'details',
      '#title' => $this->t('Teaser image fields'),
      '#description' => $this->t('Select which field should be used as the teaser image for each content type.'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];

    // Get all node types.
    $node_types = $this->entityTypeManager
      ->getStorage('node_type')
      ->loadMultiple();

    foreach ($node_types as $type_id => $type) {
      $image_fields = $this->getImageFields($type_id);

      if (empty($image_fields)) {
        $form['teaser_image_fields'][$type_id] = [
          '#type' => 'item',
          '#title' => $type->label(),
          '#markup' => '<em>' . $this->t('No image or media fields available.') . '</em>',
        ];
        continue;
      }

      $options = ['' => $this->t('- None -')] + $image_fields;

      $form['teaser_image_fields'][$type_id] = [
        '#type' => 'select',
        '#title' => $type->label(),
        '#options' => $options,
        '#default_value' => $teaser_image_fields[$type_id] ?? '',
      ];
    }

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $teaser_image_fields = $form_state->getValue('teaser_image_fields');

    // Filter out empty values.
    $teaser_image_fields = array_filter($teaser_image_fields, function ($value) {
      return !empty($value);
    });

    $this->config('nodehive_content.settings')
      ->set('teaser_image_fields', $teaser_image_fields)
      ->save();

    parent::submitForm($form, $form_state);
  }

  /**
   * Gets image and media fields for a content type.
   *
   * @param string $bundle
   *   The content type machine name.
   *
   * @return array
   *   Array of field labels keyed by field name.
   */
  protected function getImageFields($bundle) {
    $fields = [];
    $field_definitions = $this->entityFieldManager->getFieldDefinitions('node', $bundle);

    foreach ($field_definitions as $field_name => $field_definition) {
      // Skip base fields.
      if ($field_definition->getFieldStorageDefinition()->isBaseField()) {
        continue;
      }

      $field_type = $field_definition->getType();

      // Include image fields.
      if ($field_type === 'image') {
        $fields[$field_name] = $field_definition->getLabel() . ' (' . $this->t('Image') . ')';
      }

      // Include entity reference fields that reference media.
      if ($field_type === 'entity_reference') {
        $settings = $field_definition->getSettings();
        if (isset($settings['target_type']) && $settings['target_type'] === 'media') {
          $fields[$field_name] = $field_definition->getLabel() . ' (' . $this->t('Media') . ')';
        }
      }
    }

    return $fields;
  }

}
