<?php

namespace Drupal\castorcito\Form;

use Drupal\castorcito\CastorcitoComponentInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form for deleting an component field.
 *
 * @internal
 */
class CastorcitoComponentDisplaySettingsDeleteForm extends ConfirmFormBase {

  /**
   * The Component.
   *
   * @var \Drupal\castorcito\CastorcitoComponentInterface
   */
  protected $component;

  /**
   * The field name settings.
   *
   */
  protected $fieldName;

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to delete the option @field of the display setting from the @component component?', [
      '@field' => $this->component->get('display_settings')[$this->fieldName]['label'],
      '@component' => $this->component->label(),
    ]);
  }

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

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return $this->component->toUrl('edit-form');
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?CastorcitoComponentInterface $castorcito_component = NULL, $field_name = NULL) {
    $this->component = $castorcito_component;
    $this->fieldName = $field_name;

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $settings = $this->component->get('display_settings');

    if (!empty($settings[$this->fieldName])) {
      unset($settings[$this->fieldName]);
      $this->component->set('display_settings', $settings);
    }

    $this->component->save();
    $this->messenger()->addStatus($this->t('The @field option has been removed from the component display settings', ['@field' => $this->fieldName]));
    $form_state->setRedirectUrl($this->component->toUrl('edit-form'));
  }

}
