<?php

namespace Drupal\bootstrap_ui_kit\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Configure Bootstrap UI Kit settings.
 */
class BootstrapUiKitSettingsForm extends ConfigFormBase {

  /**
   * Config settings.
   *
   * @var string
   */
  const SETTINGS = 'bootstrap_ui_kit.settings';

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bootstrap_ui_kit_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      static::SETTINGS,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config(static::SETTINGS);

    $form['enable_dev_kit'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable Developer Kit'),
      '#default_value' => $config->get('enable_dev_kit'),
      '#description' => $this->t('Displays example implementations for developers on the UI Kit.'),
    ];

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

    $form['iconography']['icons_source_folder'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Icons source folder'),
      '#default_value' => $config->get('icons_source_folder'),
    ];

    $form['iconography']['icons_sprite_file'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Icons sprite file'),
      '#default_value' => $config->get('icons_sprite_file'),
    ];

    // Load available icons from filesystem.
    $icons_source_folder = $form['iconography']['icons_source_folder']['#default_value'];
    $directory = DRUPAL_ROOT . $icons_source_folder;
    $iconography_set = [];

    if (is_dir($directory)) {
      foreach (new \DirectoryIterator($directory) as $file_info) {
        if ($file_info->isFile() && $file_info->getExtension() === 'svg') {
          $iconography_set[] = pathinfo($file_info->getFilename(), PATHINFO_FILENAME);
        }
      }
    }

    $selected_icons = $config->get('selected_icons') ?? [];
    $icons_total = count($iconography_set);

    $form['#attached']['drupalSettings']['bootstrap_ui_kit']['icons'] = $iconography_set;
    $form['#attached']['drupalSettings']['bootstrap_ui_kit']['icons_total'] = $icons_total;
    $form['#attached']['drupalSettings']['bootstrap_ui_kit']['icons_sprite_file'] = $form['iconography']['icons_sprite_file']['#default_value'];
    $form['#attached']['drupalSettings']['bootstrap_ui_kit']['selected_icons'] = $selected_icons;
    $form['#attached']['library'][] = 'bootstrap_ui_kit/bootstrap_ui_kit.admin_icons';

    // Toolbar container.
    $form['iconography']['icon_toolbar'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['admin-icons-toolbar'],
      ],
    ];

    $form['iconography']['icon_toolbar']['heading'] = [
      '#markup' => '<h3>' . $this->t('Select the icons (@count total)', ['@count' => $icons_total]) . '</h3>',
    ];

    $form['iconography']['icon_toolbar']['controls'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['admin-icons-toolbar__controls'],
      ],
    ];

    $form['iconography']['icon_toolbar']['controls']['admin_icons_search'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Search icons'),
      '#title_display' => 'invisible',
      '#attributes' => [
        'id' => 'admin-icons-search',
        'placeholder' => $this->t('Search icons...'),
        'autocomplete' => 'off',
      ],
      '#size' => 25,
    ];

    // Build page size options — only show values less than total.
    $page_sizes = [25, 50, 100, 250, 500];
    $options = [];
    foreach ($page_sizes as $size) {
      if ($size < $icons_total) {
        $options[$size] = (string) $size;
      }
    }
    $options['all'] = $this->t('- All -');

    $form['iconography']['icon_toolbar']['controls']['admin_icons_page_size'] = [
      '#type' => 'select',
      '#title' => $this->t('Icons per page'),
      '#title_display' => 'invisible',
      '#options' => $options,
      '#attributes' => [
        'id' => 'admin-icons-page-size',
      ],
    ];

    // Main container for the grid (icons rendered via JS).
    $form['iconography']['icon_selection_wrapper'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'iconography-selection-wrapper',
        'class' => ['admin-icons-grid'],
      ],
    ];

    $form_state->set('available_icons', $iconography_set);

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $icons_source = (string) $form_state->getValue('icons_source_folder');
    $icons_sprite = (string) $form_state->getValue('icons_sprite_file');

    // Normalize paths: ensure leading slash, no trailing slash.
    if ($icons_source !== '') {
      $icons_source = '/' . ltrim($icons_source, '/');
      $icons_source = rtrim($icons_source, '/');
    }
    if ($icons_sprite !== '') {
      $icons_sprite = '/' . ltrim($icons_sprite, '/');
    }

    $selected_icons = [];
    $input = $form_state->getUserInput();
    foreach ($form_state->get('available_icons') ?? [] as $icon) {
      if (!empty($input[$icon])) {
        $selected_icons[] = $icon;
      }
    }

    $this->config(static::SETTINGS)
      ->set('enable_dev_kit', (bool) $form_state->getValue('enable_dev_kit'))
      ->set('icons_source_folder', $icons_source)
      ->set('icons_sprite_file', $icons_sprite)
      ->set('selected_icons', $selected_icons)
      ->save();

    parent::submitForm($form, $form_state);
  }
}
