<?php

declare(strict_types=1);

namespace Drupal\native_observability_report\Form;

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

/**
 * Configuration form for Native Observability Report.
 */
final class ObservabilityReportSettingsForm extends ConfigFormBase {

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

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

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

    $form['description'] = [
      '#type' => 'item',
      '#markup' => $this->t('Configure the default narrative source, language fallback behavior, privacy defaults, and report generation preferences for Native Observability Report.'),
    ];

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

    $form['narrative']['use_custom_narrative_file'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Use a custom narrative YAML file'),
      '#default_value' => (bool) $config->get('use_custom_narrative_file'),
      '#description' => $this->t('When enabled, the report module will attempt to load report narrative definitions from the custom path below before falling back to its bundled defaults.'),
    ];

    $form['narrative']['custom_narrative_file_path'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Custom narrative YAML file path'),
      '#default_value' => (string) ($config->get('custom_narrative_file_path') ?? ''),
      '#maxlength' => 1024,
      '#description' => $this->t('Provide an absolute path or a Drupal stream wrapper path such as private://observability/report_messages.en.yml.'),
      '#states' => [
        'visible' => [
          ':input[name="use_custom_narrative_file"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['narrative']['fallback_language'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Fallback language'),
      '#default_value' => (string) ($config->get('fallback_language') ?? 'en'),
      '#maxlength' => 12,
      '#required' => TRUE,
      '#description' => $this->t('Language code used when the preferred narrative language file is not available.'),
    ];

    $form['narrative']['strict_fallback'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable strict fallback handling'),
      '#default_value' => (bool) $config->get('strict_fallback'),
      '#description' => $this->t('When enabled, the report builder will use strict language fallback rules and avoid silently reading unrelated files.'),
    ];

    $form['defaults'] = [
      '#type' => 'details',
      '#title' => $this->t('Default report behavior'),
      '#open' => TRUE,
    ];

    $form['defaults']['default_detail_level'] = [
      '#type' => 'select',
      '#title' => $this->t('Default detail level'),
      '#default_value' => (string) ($config->get('default_detail_level') ?? 'intermediate'),
      '#options' => [
        'basic' => $this->t('Basic'),
        'intermediate' => $this->t('Intermediate'),
        'advanced' => $this->t('Advanced'),
      ],
      '#description' => $this->t('Defines the default explanation depth used when building a new report.'),
    ];

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

    $form['privacy']['default_mask_user_identifiers'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Mask user identifiers by default'),
      '#default_value' => (bool) $config->get('default_mask_user_identifiers'),
    ];

    $form['privacy']['default_hide_ip_addresses'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Hide IP addresses by default'),
      '#default_value' => (bool) $config->get('default_hide_ip_addresses'),
    ];

    $form['privacy']['default_hide_route_parameters'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Hide route parameters by default'),
      '#default_value' => (bool) $config->get('default_hide_route_parameters'),
    ];

    $form['privacy']['default_include_overhead_section'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Include the observability overhead section by default'),
      '#default_value' => (bool) $config->get('default_include_overhead_section'),
    ];

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

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state): void {
    if ((bool) $form_state->getValue('use_custom_narrative_file')) {
      $path = trim((string) $form_state->getValue('custom_narrative_file_path'));
      if ($path === '') {
        $form_state->setErrorByName('custom_narrative_file_path', $this->t('A custom narrative file path is required when the custom narrative option is enabled.'));
      }
    }

    $fallback = trim((string) $form_state->getValue('fallback_language'));
    if ($fallback === '') {
      $form_state->setErrorByName('fallback_language', $this->t('The fallback language cannot be empty.'));
    }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->configFactory->getEditable('native_observability_report.settings')
      ->set('use_custom_narrative_file', (bool) $form_state->getValue('use_custom_narrative_file'))
      ->set('custom_narrative_file_path', trim((string) $form_state->getValue('custom_narrative_file_path')))
      ->set('fallback_language', trim((string) $form_state->getValue('fallback_language')))
      ->set('strict_fallback', (bool) $form_state->getValue('strict_fallback'))
      ->set('default_detail_level', (string) $form_state->getValue('default_detail_level'))
      ->set('default_mask_user_identifiers', (bool) $form_state->getValue('default_mask_user_identifiers'))
      ->set('default_hide_ip_addresses', (bool) $form_state->getValue('default_hide_ip_addresses'))
      ->set('default_hide_route_parameters', (bool) $form_state->getValue('default_hide_route_parameters'))
      ->set('default_include_overhead_section', (bool) $form_state->getValue('default_include_overhead_section'))
      ->save();

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

}
