<?php

namespace Drupal\sector_embedded_content_examples\Plugin\EmbeddedContent;

use Drupal\embedded_content\EmbeddedContentInterface;
use Drupal\embedded_content\EmbeddedContentPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Plugin disclosure.
 *
 * @EmbeddedContent(
 *   id = "sector.disclosure",
 *   label = @Translation("Disclosure"),
 *   description = @Translation("Renders a Disclosure component."),
 * )
 */
class Disclosure extends EmbeddedContentPluginBase implements EmbeddedContentInterface {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'body' => '',
      'summary' => NULL,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function build(): array {
    return [
      '#type' => 'component',
      '#component' => 'sector_embedded_content_examples:disclosure',
      '#properties' => [
        'utility_classes' => [],
      ],
      '#slots' => [
        'summary' => $this->configuration['summary'],
        'body' => check_markup($this->configuration['body']['value'], $this->configuration['body']['format']) ?? '',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {

    $form['summary'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Summary'),
      '#default_value' => $this->configuration['summary'],
      '#description' => $this->t('Renders inside a summary element.'),
    ];

    $form['body'] = [
      '#type' => 'text_format',
      '#allowed_formats' => ['sector_restricted_basic_html'],
      '#title' => $this->t('Body'),
      '#default_value' => $this->configuration['body']['value'] ?? '',
      '#required' => TRUE,
      '#rows' => 3,
      '#description' => $this->t('Renders inside a details element.'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $body = check_markup($form_state->getValue('body'), 'sector_restricted_basic_html');

    $this->configuration['body'] = $body;
  }

  /**
   * {@inheritdoc}
   */
  public function isInline(): bool {
    return FALSE;
  }

}
