<?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 note.
 *
 * @EmbeddedContent(
 *   id = "sector.note",
 *   label = @Translation("Note"),
 *   description = @Translation("Renders a Notice component."),
 * )
 */
class Note extends EmbeddedContentPluginBase implements EmbeddedContentInterface {

  use StringTranslationTrait;

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

  /**
   * {@inheritdoc}
   */
  public function build(): array {
    return [
      '#theme' => 'note',
      '#heading' => $this->configuration['heading'],
      '#message' => check_markup($this->configuration['message']['value'], $this->configuration['message']['format']) ?? '',
      '#type' => $this->configuration['type']
    ];
  }

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

    $form['type'] = [
      '#type' => 'select',
      '#title' => $this->t('Note level'),
      '#default_value' => $this->configuration['type'] ?? 'note--base',
      '#required' => TRUE,
      '#options' => [
        'note--base' => $this->t('Base'),
        'note--moderate' => $this->t('Moderate'),
        'note--critical' => $this->t('Critical'),
        'note--highly-critical' => $this->t('Highly critical'),
      ]
    ];

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

    $form['message'] = [
      '#type' => 'text_format',
      '#allowed_formats' => [ 'sector_restricted_basic_html' ],
      '#title' => $this->t('Message'),
      '#default_value' => $this->configuration['message']['value'] ?? '',
      '#required' => TRUE,
      '#rows' => 3,
    ];

    return $form;
  }

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

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

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


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

}
