<?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 [
      '#type' => 'component',
      '#component' => 'sector_embedded_content_examples:note',
      '#slots' => [
        'heading' => $this->configuration['heading'],
        'message' => check_markup($this->configuration['message']['value'], $this->configuration['message']['format']) ?? '',
      ],
      '#variant' => $this->configuration['type'],
      '#properties' => [
        'utility_classes' => [],
      ],
    ];
  }

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

    $form['type'] = [
      '#type' => 'select',
      '#title' => $this->t('Note level'),
      '#default_value' => $this->configuration['type'] ?? 'base',
      '#required' => TRUE,
      '#options' => [
        'base' => $this->t('Base'),
        'moderate' => $this->t('Moderate'),
        'critical' => $this->t('Critical'),
        '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;
  }

}
