<?php

declare(strict_types=1);

namespace Drupal\sobki_admin\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\layout_builder\OverridesSectionStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Alter forms.
 */
class FormAlter implements ContainerInjectionInterface {

  /**
   * Place the edit template link at last position in actions.
   */
  public const EDIT_TEMPLATE_WEIGHT = 100;

  public function __construct(
    protected EntityTypeBundleInfoInterface $entityTypeBundleInfo,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('entity_type.bundle.info'),
    );
  }

  use StringTranslationTrait;

  /**
   * Alter forms.
   *
   * @param array $form
   *   The form structure.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The form state.
   * @param string $form_id
   *   The form ID.
   */
  public function alter(array &$form, FormStateInterface $formState, string $form_id): void {
    // Default styling for Layout Builder "main" form.
    // There is no specific form ID to target as the base form ID is dynamic in
    // LayoutBuilderEntityFormTrait.
    if (\str_ends_with($form_id, '_layout_builder_form')) {
      $this->alterLayoutBuilderForm($form, $formState);
    }
  }

  /**
   * Default styling for Layout Builder "main" form.
   *
   * @param array $form
   *   The form structure.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The form state.
   */
  protected function alterLayoutBuilderForm(array &$form, FormStateInterface $formState): void {
    // Close revision information by default.
    if (isset($form['revision_information'])) {
      $form['revision_information']['#open'] = FALSE;
    }

    // Hide native message.
    if (isset($form['layout_builder_message'])) {
      $form['layout_builder_message']['#access'] = FALSE;
    }

    // Add a link to edit template if available.
    /** @var \Drupal\layout_builder\Form\UpdateBlockForm $form_object */
    $form_object = $formState->getFormObject();
    $sectionStorage = $form_object->getSectionStorage();
    if (!($sectionStorage instanceof OverridesSectionStorageInterface)) {
      return;
    }
    $defaults_link = $sectionStorage
      ->getDefaultSectionStorage()
      ->getLayoutBuilderUrl();
    if (!$defaults_link->access()) {
      return;
    }
    $entity = $sectionStorage->getContextValue('entity');
    if (!($entity instanceof EntityInterface)) {
      return;
    }
    $entity_type = $entity->getEntityType();
    $bundle_info = $this->entityTypeBundleInfo->getBundleInfo($entity->getEntityTypeId());

    $form['actions']['edit_template'] = [
      '#type' => 'link',
      '#url' => $defaults_link,
      '#title' => $entity_type->hasKey('bundle')
        ? $this->t('Edit @bundle template', ['@bundle' => $bundle_info[$entity->bundle()]['label']])
        : $this->t('Edit template'),
      '#weight' => static::EDIT_TEMPLATE_WEIGHT,
    ];
  }

}
