<?php

namespace Drupal\castorcito\Plugin\CastorcitoComponentField;

use Drupal\Core\Form\FormStateInterface;
use Drupal\castorcito\ConfigurableComponentFieldBase;

/**
 * Provides configuration for a container field.
 *
 * @CastorcitoComponentField(
 *   id = "container",
 *   label = @Translation("Container"),
 *   description = @Translation("Configuration for the container field.")
 * )
 */
class Container extends ConfigurableComponentFieldBase {

  /**
   * {@inheritdoc}
   */
  public function defaultModel() {
    return [
      'items' => [],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'allowed_children' => [],
      'min' => 1,
      'max' => 1,
      'add_button_label' => 'Add',
      'delete_button_label' => 'Delete',
      'collapse_container' => 0,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['allowed_children'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Allowed Components'),
      '#options' => $this->componentList(),
      '#default_value' => $this->configuration['allowed_children'],
      '#description' => $this->t('Choose necessary components for the container, you need to have a component already created.'),
      '#required' => TRUE,
      '#multiple' => TRUE,
    ];

    $form['min'] = [
      '#type' => 'number',
      '#title' => $this->t('Limit min'),
      '#default_value' => $this->configuration['min'],
      '#description' => $this->t('Allows you to define a limit min.'),
    ];

    $form['max'] = [
      '#type' => 'number',
      '#title' => $this->t('Limit max'),
      '#default_value' => $this->configuration['max'],
      '#description' => $this->t('Allows you to define a limit max.'),
    ];

    $form['add_button_label'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Add button label'),
      '#default_value' => $this->configuration['add_button_label'],
      '#description' => $this->t('Enter the label text to display on the button for adding more items.'),
    ];

    $form['delete_button_label'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Delete button label'),
      '#default_value' => $this->configuration['delete_button_label'],
      '#description' => $this->t('Enter the label text to displayed on the button to delete the element.'),
    ];

    $form['collapse_container'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Collapse container, set <strong>close</strong> by default'),
      '#default_value' => $this->configuration['collapse_container'],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    if (empty($form_state->getValue('allowed_children'))) {
      $form_state->setErrorByName('allowed_children', $this->t('No components are available. Please add a component to use this field.'));
    }

    if (empty($form_state->getValue('add_button_label')) || empty($form_state->getValue('delete_button_label'))) {
      $form_state->setErrorByName('button_label', $this->t('Please enter a label for the button.'));
    }

    $limit_min = $form_state->getValue('min');
    $limit_max = $form_state->getValue('max');

    if ($limit_min < 1 || $limit_max < 1) {
      $form_state->setErrorByName('limit', $this->t('Both minimum and maximum limits must be greater than 0.'));
    }

    if ($limit_min > $limit_max) {
      $form_state->setErrorByName('limit', $this->t('The maximum limit must be greater than or equal to the minimum limit.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['allowed_children'] = array_filter($form_state->getValue('allowed_children'));
    $this->configuration['min'] = $form_state->getValue('min');
    $this->configuration['max'] = $form_state->getValue('max');
    $this->configuration['add_button_label'] = $form_state->getValue('add_button_label');
    $this->configuration['delete_button_label'] = $form_state->getValue('delete_button_label');
    $this->configuration['collapse_container'] = $form_state->getValue('collapse_container');
  }

  /**
   * {@inheritdoc}
   */
  public function overridableConfiguration() {
    return parent::overridableConfiguration() + [
      'min',
      'max',
      'add_button_label',
      'delete_button_label',
      'collapse_container',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function componentList() {
    $definitions = $this->componentStorage->loadMultiple();
    $components = [];

    if (!empty($definitions)) {
      foreach ($definitions as $id => $definition) {
        $is_container = $this->fieldIsContainer($definition->getModel());

        if (!$is_container) {
          $components[$id] = $definition->label();
        }
      }
    }

    if (!empty($this->component)) {
      return array_diff_key($components, [$this->component->id() => NULL]);
    }

    return $components;
  }

  /**
   * {@inheritdoc}
   */
  private function fieldIsContainer($model) {
    $is_container = [
      'container',
      'advanced_container'
    ];

    if (!empty($model) && isset($model['fields']) && !empty($model['fields'])) {
      foreach ($model['fields'] as $field) {
        if (in_array($field['type'], $is_container)) {
          return TRUE;
        }
      }
    }

    return FALSE;
  }

}
