<?php

declare(strict_types=1);

namespace Drupal\flowdrop\Form;

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

/**
 * Central settings form for FlowDrop configuration.
 *
 * This form provides a single location for managing FlowDrop-wide settings
 * that affect the entire ecosystem, including logging, performance, and
 * behavior options.
 */
class FlowDropSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames(): array {
    return ['flowdrop.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'flowdrop_settings_form';
  }

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

    // Logging Settings.
    $form['logging'] = [
      '#type' => 'details',
      '#title' => $this->t('Logging'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];

    $form['logging']['log_verbosity'] = [
      '#type' => 'select',
      '#title' => $this->t('Logging Verbosity'),
      '#description' => $this->t('Controls the amount of detail logged during workflow and node execution.'),
      '#options' => [
        'silent' => $this->t('Silent - No execution logging'),
        'minimal' => $this->t('Minimal - Errors only'),
        'standard' => $this->t('Standard - Workflow/node start and completion (default)'),
        'verbose' => $this->t('Verbose - Include parameter summaries and warnings'),
        'debug' => $this->t('Debug - Full parameter dumps and stack traces'),
      ],
      '#default_value' => $config->get('logging.verbosity') ?? 'standard',
    ];

    $form['logging']['log_to_watchdog'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Log to Drupal watchdog'),
      '#description' => $this->t('When enabled, execution logs are written to Drupal"s database log (dblog).'),
      '#default_value' => $config->get('logging.log_to_watchdog') ?? TRUE,
    ];

    // Execution Settings.
    $form['execution'] = [
      '#type' => 'details',
      '#title' => $this->t('Execution'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['execution']['default_orchestrator'] = [
      '#type' => 'select',
      '#title' => $this->t('Default Orchestrator'),
      '#description' => $this->t('The default orchestrator to use for workflow execution.'),
      '#options' => [
        'synchronous' => $this->t('Synchronous - Execute all nodes in sequence'),
        'asynchronous' => $this->t('Asynchronous - Queue-based background execution'),
      ],
      '#default_value' => $config->get('execution.default_orchestrator') ?? 'synchronous',
    ];

    $form['execution']['max_execution_time'] = [
      '#type' => 'number',
      '#title' => $this->t('Maximum Execution Time'),
      '#description' => $this->t('Maximum time (in seconds) a single node can execute before timeout. Set to 0 for no limit.'),
      '#min' => 0,
      '#max' => 3600,
      '#default_value' => $config->get('execution.max_execution_time') ?? 300,
      '#field_suffix' => $this->t('seconds'),
    ];

    // Real-time Updates Settings.
    $form['realtime'] = [
      '#type' => 'details',
      '#title' => $this->t('Real-time Updates'),
      '#open' => FALSE,
      '#access' => FALSE,
      '#tree' => TRUE,
    ];

    $form['realtime']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable real-time status updates'),
      '#description' => $this->t('When enabled, workflow execution status is broadcast in real-time to connected clients.'),
      '#default_value' => $config->get('realtime.enabled') ?? TRUE,
    ];

    $form['realtime']['polling_interval'] = [
      '#type' => 'number',
      '#title' => $this->t('Polling Interval'),
      '#description' => $this->t('How often (in milliseconds) clients should poll for status updates when SSE is unavailable.'),
      '#min' => 0,
      '#max' => 30000,
      '#default_value' => $config->get('realtime.polling_interval') ?? 2000,
      '#field_suffix' => $this->t('ms'),
      '#states' => [
        'visible' => [
          ':input[name="realtime[enabled]"]' => ['checked' => TRUE],
        ],
      ],
    ];

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->config('flowdrop.settings')
      ->set('logging.verbosity', $form_state->getValue(['logging', 'log_verbosity']))
      ->set('logging.log_to_watchdog', (bool) $form_state->getValue(['logging', 'log_to_watchdog']))
      ->set('execution.default_orchestrator', $form_state->getValue(['execution', 'default_orchestrator']))
      ->set('execution.max_execution_time', (int) $form_state->getValue(['execution', 'max_execution_time']))
      ->set('realtime.enabled', (bool) $form_state->getValue(['realtime', 'enabled']))
      ->set('realtime.polling_interval', (int) $form_state->getValue(['realtime', 'polling_interval']))
      ->save();

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

}
