<?php

namespace Drupal\component_builder_toolbar\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseDialogCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Provides a form to delete component wrapper item.
 *
 * @internal
 */
class ComponentWrapperDeleteItem extends ConfirmFormBase {

  /**
   * The component wrapper.
   *
   * @var \Drupal\component_builder\Entity\ComponentWrapper
   */
  protected $componentWrapper;

  /**
   * The entity.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

  /**
   * The entity type id.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * The field name.
   *
   * @var string
   */
  protected $fieldName;


  /**
   * The field label.
   *
   * @var string
   */
  protected $fieldLabel;

  /**
   * The delta.
   *
   * @var string
   */
  protected $delta;

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to delete %item?', ['%item' => $this->fieldLabel]);
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this->t('Delete');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('<front>');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $entity_type_id = '', $component_wrapper = '', $field_name = '', $delta = '') {
    $this->entityTypeId = $entity_type_id;
    $this->fieldName = $field_name;
    $this->delta = $delta;
    $this->componentWrapper = $component_wrapper;
    $this->fieldLabel = $component_wrapper->label();
    $this->entity = $this->getRequest()->get($entity_type_id);
    $form = parent::buildForm($form, $form_state);
    $form['actions']['submit']['#ajax'] = [
      'callback' => [$this, 'submitCallback'],
    ];
    $form['actions']['cancel']['#ajax'] = [
      'callback' => [$this, 'cancelCallback'],
    ];
    $form['actions']['cancel']['#type'] = 'button';
    $form['actions']['cancel']['#value'] = 'Cancel';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $field_values = $this->entity->get($this->fieldName)->getValue();
    array_splice($field_values, $this->delta, 1);
    $this->entity->set($this->fieldName, $field_values)->save();
  }

  /**
   * Submit field ajax.
   */
  public function submitCallback(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $wrapper_selector = "[data-wrapper-id='{$this->componentWrapper->id()}']";
    $response->addCommand(new ReplaceCommand($wrapper_selector, ""));
    /** @var \Drupal\component_builder\Entity\ComponentWrapperInterface[] $referenced_component_wrappers */
    $referenced_component_wrappers = $this->entity->get($this->fieldName)->referencedEntities();
    foreach ($referenced_component_wrappers as $delta => $referenced_component_wrapper) {
      if ($delta >= $this->delta) {
        $wrapper_selector = "[data-wrapper-id='{$referenced_component_wrapper->id()}']";
        $move_wrapper_url = Url::fromRoute(
          'entity.' . $this->entityTypeId . '.component_builder_toolbar_move_component',
          [
            $this->entityTypeId => $this->entity->id(),
            'component_wrapper' => $referenced_component_wrapper->id(),
            'field_name' => $this->fieldName,
          ]
        );
        $wrapper_markup = \Drupal::service('component_builder_toolbar.manager')->buildComponentWrapperMarkup($this->entity, $referenced_component_wrapper, $move_wrapper_url, $delta);
        $response->addCommand(new ReplaceCommand($wrapper_selector, $wrapper_markup));
      }
    }
    $response->addCommand(new CloseDialogCommand());
    return $response;
  }

  /**
   * Cancel submit delete field ajax.
   */
  public function cancelCallback(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new CloseDialogCommand());
    return $response;
  }

}
