<?php

declare(strict_types=1);

namespace Drupal\layout_builder_browser_library\HookHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\layout_builder_browser\Entity\LayoutBuilderBrowserBlock;

/**
 * Layout Builder browser block form alter.
 */
class FormLayoutBuilderBrowserBlockAlter {

  use StringTranslationTrait;

  /**
   * Add settings on block 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_browser\Form\BlockForm $formObject */
    $formObject = $formState->getFormObject();
    /** @var \Drupal\layout_builder_browser\Entity\LayoutBuilderBrowserBlock $entity */
    $entity = $formObject->getEntity();
    $settings = $entity->getThirdPartySettings('layout_builder_browser_library');

    $form['layout_builder_browser_library'] = [
      '#type' => 'details',
      '#title' => $this->t('Library'),
      '#tree' => TRUE,
    ];

    $form['layout_builder_browser_library']['description'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Description'),
      '#description' => $this->t('This description is used for the Layout Builder Browser block library.'),
      '#default_value' => $settings['description'] ?? '',
    ];

    $form['layout_builder_browser_library']['library_image_path'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Library image path'),
      '#default_value' => $settings['library_image_path'] ?? '',
      '#description' => $this->t('This image is used for the Layout Builder Browser block library. E.g. /themes/my_custom_theme/images/lbb/text.jpg'),
    ];
    $form['layout_builder_browser_library']['library_image_alt'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Library image alt'),
      '#default_value' => $settings['library_image_alt'] ?? '',
    ];

    $form['#entity_builders'][] = [$this, 'entityBuilder'];
  }

  /**
   * Save third party settings.
   */
  public function entityBuilder(string $entityType, LayoutBuilderBrowserBlock $entity, array &$form, FormStateInterface $formState): void {
    $settings = $formState->getValue('layout_builder_browser_library');
    if (!\is_array($settings)) {
      return;
    }
    foreach ($settings as $key => $value) {
      $entity->setThirdPartySetting('layout_builder_browser_library', $key, $value);
    }
  }

}
