<?php

namespace Drupal\castorcito\Plugin\CastorcitoComponentField;

use Drupal\castorcito\ConfigurableComponentFieldBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\StringTranslation\ByteSizeMarkup;
use Drupal\Component\Utility\Environment;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides configuration for an image field.
 *
 * @CastorcitoComponentField(
 *   id = "image",
 *   label = @Translation("Imagen"),
 *   description = @Translation("Configuration for the image field.")
 * )
 */
class Image extends ConfigurableComponentFieldBase {

  /**
   * {@inheritdoc}
   */
  public function defaultModel() {
    return [
      'fid' => '',
      'name' => '',
      'size' => '',
      'value' => '',
      'thumbnail' => '',
      'title' => '',
      'alt' => '',
      'width' => '',
      'height' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $default_max_size = ByteSizeMarkup::create(Environment::getUploadMaxSize());

    return parent::defaultConfiguration() + [
      'extensions' => 'png, jpg, jpeg, webp',
      'directory' => 'castorcito-images',
      'max_size' => $default_max_size,
      'uri_scheme' => 'public',
      'max_dimensions' => [
        'width' => '',
        'height' => '',
      ],
      'alt_field' => 1,
      'alt_field_required' => 1,
      'title_field' => 0,
      'title_field_required' => 0,
      'display' => [],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $scheme_options = \Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE);
    $form['uri_scheme'] = [
      '#type' => 'radios',
      '#title' => $this->t('Upload destination'),
      '#options' => $scheme_options,
      '#default_value' => $this->configuration['uri_scheme'],
      '#description' => $this->t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
    ];

    $form['extensions'] = [
      '#type' => 'textfield',
      '#default_value' => $this->configuration['extensions'],
      '#title' => $this->t('Allowed file extensions'),
      '#description' => $this->t("Separate extensions with a comma or space. Each extension can contain alphanumeric characters, '.', and '_', and should start and end with an alphanumeric character."),
    ];

    $form['directory'] = [
      '#type' => 'textfield',
      '#default_value' => $this->configuration['directory'],
      '#title' => $this->t('Upload directory'),
      '#description' => $this->t("A directory relative to Drupal's files directory where uploaded images will be stored."),
    ];

    $default_max_size = ByteSizeMarkup::create(Environment::getUploadMaxSize());
    $form['max_size'] = [
      '#type' => 'textfield',
      '#default_value' => $this->configuration['max_size'],
      '#title' => $this->t('Maximum file size'),
      '#description' => $this->t('If this is left empty, then the file size will be limited by the PHP maximum upload size of @size.', ['@size' => $default_max_size]),
      '#maxlength' => 20,
      '#size' => 10,
      '#placeholder' => $default_max_size,
    ];

    $form['max_dimensions'] = [
      '#type' => 'item',
      '#title' => $this->t('Maximum dimensions'),
      '#description' => $this->t('Images larger than these dimensions will be scaled down.'),
      '#tree' => TRUE,
    ];

    $form['max_dimensions']['width'] = [
      '#title' => $this->t('Width'),
      '#title_display' => 'invisible',
      '#type' => 'number',
      '#default_value' => $this->configuration['max_dimensions']['width'],
      '#size' => 8,
      '#maxlength' => 8,
      '#min' => 1,
      '#max' => 99999,
      '#placeholder' => $this->t('width'),
      '#field_suffix' => ' x ',
      '#prefix' => '<div class="form--inline clearfix">',
    ];

    $form['max_dimensions']['height'] = [
      '#title' => $this->t('Height'),
      '#title_display' => 'invisible',
      '#type' => 'number',
      '#default_value' => $this->configuration['max_dimensions']['height'],
      '#size' => 8,
      '#maxlength' => 8,
      '#min' => 1,
      '#max' => 99999,
      '#placeholder' => $this->t('height'),
      '#suffix' => '</div>',
    ];

    $form['alt_field'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable <em>Alt</em> field'),
      '#default_value' => $this->configuration['alt_field'],
      '#description' => $this->t('Short description of the image used by screen readers and displayed when the image is not loaded. Enabling this field is recommended.'),
    ];

    $form['alt_field_required'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('<em>Alt</em> field required'),
      '#default_value' => $this->configuration['alt_field_required'],
      '#description' => $this->t('Making this field required is recommended.'),
      '#states' => [
        'visible' => [
          ':input[name="settings[alt_field]"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['title_field'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable <em>Title</em> field'),
      '#default_value' => $this->configuration['title_field'],
      '#description' => $this->t('The title attribute is used as a tooltip when the mouse hovers over the image. Enabling this field is not recommended as it can cause problems with screen readers.'),
    ];

    $form['title_field_required'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('<em>Title</em> field required'),
      '#default_value' => $this->configuration['title_field_required'],
      '#states' => [
        'visible' => [
          ':input[name="settings[title_field]"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['display'] = [
      '#type' => 'details',
      '#title' => $this->t('Display'),
      '#open' => TRUE,
    ];

    $image_styles = image_style_options(FALSE);
    $form['display']['image_style'] = [
      '#title' => $this->t('Image style'),
      '#type' => 'select',
      '#default_value' => $this->configuration['display']['image_style'] ?? NULL,
      '#empty_option' => $this->t('None (original image)'),
      '#options' => $image_styles,
    ];

    $form['display']['image_loading'] = [
      '#type' => 'details',
      '#title' => $this->t('Image loading'),
      '#weight' => 10,
      '#description' => $this->t('Lazy render images with native image loading attribute (<em>loading="lazy"</em>). This improves performance by allowing browsers to lazily load images.'),
      '#tree' => TRUE,
    ];

    $loading_attribute_options = [
      'lazy' => $this->t('Lazy (<em>loading="lazy"</em>)'),
      'eager' => $this->t('Eager (<em>loading="eager"</em>)'),
    ];
    $form['display']['image_loading']['attribute'] = [
      '#title' => $this->t('Image loading attribute'),
      '#type' => 'radios',
      '#default_value' => $this->configuration['display']['image_loading']['attribute'] ?? 'lazy',
      '#options' => $loading_attribute_options,
      '#description' => $this->t('Select the loading attribute for images. <a href=":link">Learn more about the loading attribute for images.</a>', [
        ':link' => 'https://html.spec.whatwg.org/multipage/urls-and-fetching.html#lazy-loading-attributes',
      ]),
    ];

    $form['display']['image_loading']['attribute']['lazy']['#description'] = $this->t('Delays loading the image until that section of the page is visible in the browser. When in doubt, lazy loading is recommended.');
    $form['display']['image_loading']['attribute']['eager']['#description'] = $this->t('Force browsers to download an image as soon as possible. This is the browser default for legacy reasons. Only use this option when the image is always expected to render.');

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['uri_scheme'] = $form_state->getValue('uri_scheme');
    $this->configuration['extensions'] = $form_state->getValue('extensions');
    $this->configuration['directory'] = $form_state->getValue('directory');
    $this->configuration['max_size'] = $form_state->getValue('max_size');
    $this->configuration['max_dimensions'] = $form_state->getValue('max_dimensions');
    $this->configuration['alt_field'] = $form_state->getValue('alt_field');
    $this->configuration['alt_field_required'] = $form_state->getValue('alt_field_required');
    $this->configuration['title_field'] = $form_state->getValue('title_field');
    $this->configuration['title_field_required'] = $form_state->getValue('title_field_required');
    $this->configuration['display'] = $form_state->getValue(['display']);
  }

  /**
   * {@inheritdoc}
   */
  public function overridableConfiguration() {
    return parent::overridableConfiguration() + [
      'uri_scheme',
      'extensions',
      'directory',
      'max_size',
      'max_dimensions',
      'alt_field',
      'alt_field_required',
      'title_field',
      'title_field_required',
    ];
  }

}
