<?php

namespace Drupal\translatable_config_pages\Form;

use Drupal\Core\Entity\BundleEntityFormBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuParentFormSelectorInterface;
use Drupal\Core\Routing\RouteBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form handler for translatable config pages type forms.
 */
class TranslatableConfigPagesTypeForm extends BundleEntityFormBase {

  /**
   * Router builder.
   *
   * @var \Drupal\Core\Routing\RouteBuilderInterface
   */
  protected RouteBuilderInterface $routerBuilder;

  /**
   * The parent form selector service.
   *
   * @var \Drupal\Core\Menu\MenuParentFormSelectorInterface
   */
  protected MenuParentFormSelectorInterface $menuParentSelector;

  /**
   * Constructs a ConfigPagesForm object.
   *
   * @param \Drupal\Core\Routing\RouteBuilderInterface $router_builder
   *   The router builder.
   * @param \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector
   *   The menu parent form selector service.
   */
  public function __construct(RouteBuilderInterface $router_builder, MenuParentFormSelectorInterface $menu_parent_selector) {
    $this->routerBuilder = $router_builder;
    $this->menuParentSelector = $menu_parent_selector;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('router.builder'),
      $container->get('menu.parent_form_selector'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);

    $entity_type = $this->entity;
    if ($this->operation === 'edit') {
      $form['#title'] = $this->t('Edit %label translatable config pages type', ['%label' => $entity_type->label()]);
    }

    $form['label'] = [
      '#title' => $this->t('Label'),
      '#type' => 'textfield',
      '#default_value' => $entity_type->label(),
      '#description' => $this->t('The human-readable name of this translatable config pages type.'),
      '#required' => TRUE,
      '#size' => 30,
    ];

    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $entity_type->id(),
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#machine_name' => [
        'exists' => [
          'Drupal\translatable_config_pages\Entity\TranslatableConfigPagesType',
          'load',
        ],
        'source' => ['label'],
      ],
      '#description' => $this->t('A unique machine-readable name for this translatable config pages type. It must only contain lowercase letters, numbers, and underscores.'),
    ];

    // Menu.
    $form['menu'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Menu'),
      '#tree' => TRUE,
      '#open' => TRUE,
    ];

    $form['menu']['description'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Description'),
      '#description' => $this->t('Description will be displayed under menu link.'),
      '#default_value' => !empty($entity_type->menu['description'])
        ? $entity_type->menu['description']
        : '',
      '#required' => TRUE,
    ];

    $default = 'admin:';
    $id = '';
    $form['menu']['menu_parent'] = $this->menuParentSelector->parentSelectElement($default, $id);
    $form['menu']['menu_parent']['#required'] = TRUE;
    $form['menu']['menu_parent']['#weight'] = 10;
    $form['menu']['menu_parent']['#title'] = $this->t('Parent link');
    $form['menu']['menu_parent']['#description'] = $this->t('The maximum depth for a link and all its children is fixed. Some menu links may not be available as parents if selecting them would exceed this limit.');
    $form['menu']['menu_parent']['#attributes']['class'][] = 'menu-title-select';
    $form['menu']['menu_parent']['#default_value'] = !empty($entity_type->menu['menu_parent'])
      ? $entity_type->menu['menu_parent']
      : '';

    return $this->protectBundleIdElement($form);
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this->t('Save translatable config pages type');
    $actions['delete']['#value'] = $this->t('Delete translatable config pages type');
    return $actions;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $entity_type = $this->entity;

    $entity_type->set('id', trim($entity_type->id()));
    $entity_type->set('label', trim($entity_type->label()));

    $status = $entity_type->save();

    $t_args = ['%name' => $entity_type->label()];
    $message = '';
    if ($status === SAVED_UPDATED) {
      $message = $this->t('The translatable config pages type %name has been updated.', $t_args);
    }
    elseif ($status === SAVED_NEW) {
      $message = $this->t('The translatable config pages type %name has been added.', $t_args);
    }
    $this->messenger()->addStatus($message);

    // Rebuild routes to show new menu items.
    $this->routerBuilder->rebuild();

    $form_state->setRedirectUrl($entity_type->toUrl('collection'));
  }

}
