<?php

declare(strict_types=1);

namespace Drupal\api_monitor_client\Form;

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

/**
 * Configure api_monitor_client settings for this site.
 */
final class SettingsForm extends ConfigFormBase {

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

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

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

    $form['alert_settings'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Configurazione Alert'),
    ];

    $form['general'] = [
      '#type' => 'details',
      '#title' => $this->t('Impostazioni Generali'),
      '#group' => 'alert_settings',
    ];

    $form['general']['resend_interval'] = [
      '#type' => 'number',
      '#title' => $this->t('Intervallo di notifica (minuti)'),
      '#default_value' => $config->get('resend_interval') ?: 60,
      '#description' => $this->t('Minuti da attendere prima di inviare un nuovo alert per lo stesso errore (evita lo spam).'),
    ];

    $form['email_handler'] = [
      '#type' => 'details',
      '#title' => $this->t('Notifiche Email'),
      '#group' => 'alert_settings',
    ];

    $form['email_handler']['email_alerts_active'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Abilita notifiche via Email'),
      '#default_value' => $config->get('email_alerts_active'),
    ];

    $form['email_handler']['alert_email'] = [
      '#type' => 'email',
      '#title' => $this->t('Indirizzo Email destinatario'),
      '#default_value' => $config->get('alert_email'),
      '#states' => [
        'visible' => [
          ':input[name="email_alerts_active"]' => ['checked' => TRUE],
        ],
      ],
    ];

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->config('api_monitor_client.settings')
      ->set('resend_interval', $form_state->getValue('resend_interval'))
      ->set('email_alerts_active', $form_state->getValue('email_alerts_active'))
      ->set('alert_email', $form_state->getValue('alert_email'))
      ->save();

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

}
