<?php

declare(strict_types=1);

namespace Drupal\sobki_background_image\HookHandler;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\sobki_background_image\Form\SettingsForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Layout Builder block form alter.
 */
class FormLayoutBuilderBlockAlter implements ContainerInjectionInterface {

  use DependencySerializationTrait;
  use StringTranslationTrait;

  public function __construct(
    protected ConfigFactoryInterface $configFactory,
  ) {}

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

  /**
   * Add background image on block config form.
   *
   * @param array $form
   *   The form structure.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The form state.
   */
  public function formAlter(array &$form, FormStateInterface $formState): void {
    /** @var \Drupal\layout_builder\Form\ConfigureBlockFormBase $formObject */
    $formObject = $formState->getFormObject();
    $component = $formObject->getCurrentComponent();
    $settings = $component->get('sobki_background_image');

    $config = $this->configFactory->get(SettingsForm::CONFIG_NAME);
    $mapping = $config->get('media_bundle_mapping');
    if (!\is_array($mapping)) {
      return;
    }

    $allowedBundles = \array_keys($mapping);
    if (empty($allowedBundles)) {
      return;
    }

    $form['sobki_background_image'] = [
      '#type' => 'sobki_background_image',
      '#title' => $this->t('Background image'),
      '#media_bundles' => $allowedBundles,
      '#default_value' => $settings,
    ];

    // Our submit handler must execute before the default one, because the
    // default handler stores the section & component data in the tempstore
    // and we need to update those objects before that happens.
    if (\is_array($form['#submit'])) {
      \array_unshift($form['#submit'], [$this, 'submitForm']);
    }
  }

  /**
   * Custom submit handler for submitting Layout Builder block forms.
   *
   * Persists the configured settings to the component configuration data,
   * which is later persisted to section storage by layout builder's base form.
   */
  public function submitForm(array $form, FormStateInterface $formState): void {
    /** @var \Drupal\layout_builder\Form\ConfigureBlockFormBase $formObject */
    $formObject = $formState->getFormObject();
    $component = $formObject->getCurrentComponent();
    $component->set('sobki_background_image', $formState->getValue('sobki_background_image'));
  }

}
