<?php

declare(strict_types=1);

namespace Drupal\native_observability_database_observer\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Provides a minimal GET-based filters form for the database observer raw list.
 */
final class DatabaseObserverFiltersForm extends FormBase {

  /**
   * Creates a new database observer filters form instance.
   */
  public function __construct(
    private readonly RequestStack $databaseObserverRequestStack,
    private readonly AccountProxyInterface $databaseObserverCurrentUser,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get('request_stack'),
      $container->get('current_user'),
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $request = $this->databaseObserverRequestStack->getCurrentRequest();
    $form['#method'] = 'get';

    $form['filters'] = [
      '#type' => 'container',
      '#attributes' => [
        'style' => 'display:flex; flex-wrap:wrap; gap:16px; align-items:flex-end; margin-bottom:16px;',
      ],
    ];

    $form['filters']['search_wrapper'] = [
      '#type' => 'container',
      '#attributes' => [
        'style' => 'min-width:340px;',
      ],
    ];

    $form['filters']['search_wrapper']['search'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Search'),
      '#default_value' => $request?->query->get('search', ''),
      '#size' => 32,
      '#attributes' => [
        'placeholder' => $this->t('Route, path, request ID...'),
      ],
    ];

    $form['filters']['relation_type_wrapper'] = [
      '#type' => 'container',
      '#attributes' => [
        'style' => 'min-width:180px;',
      ],
    ];

    $form['filters']['relation_type_wrapper']['relation_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Relation type'),
      '#options' => [
        '' => $this->t('- Any -'),
        'request_bound' => $this->t('Request-bound'),
        'unrelated' => $this->t('Unrelated'),
      ],
      '#default_value' => $request?->query->get('relation_type', ''),
    ];

    $form['filters']['is_slow_wrapper'] = [
      '#type' => 'container',
      '#attributes' => [
        'style' => 'min-width:180px;',
      ],
    ];

    $form['filters']['is_slow_wrapper']['is_slow'] = [
      '#type' => 'select',
      '#title' => $this->t('Slow'),
      '#options' => [
        '' => $this->t('- Any -'),
        '1' => $this->t('Yes'),
        '0' => $this->t('No'),
      ],
      '#default_value' => $request?->query->get('is_slow', ''),
    ];

    $form['filters']['actions_wrapper'] = [
      '#type' => 'container',
      '#attributes' => [
        'style' => 'display:flex; gap:8px; align-items:flex-end; padding-top:28px;',
      ],
    ];

    $form['filters']['actions_wrapper']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Apply'),
    ];

    $form['filters']['actions_wrapper']['reset'] = [
      '#type' => 'link',
      '#title' => $this->t('Reset'),
      '#url' => Url::fromRoute('native_observability_database_observer.report'),
      '#attributes' => [
        'class' => ['button', 'button--secondary'],
      ],
    ];

    $form['filters']['actions_wrapper']['export_filtered'] = [
      '#type' => 'link',
      '#title' => $this->t('Export filtered'),
      '#url' => Url::fromRoute('native_observability_database_observer.export_filtered', [], [
        'query' => $request?->query->all() ?? [],
      ]),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];

    if ($this->databaseObserverCurrentUser->hasPermission('administer native observability database observer')) {
      $form['filters']['actions_wrapper']['delete_filtered'] = [
        '#type' => 'link',
        '#title' => $this->t('Delete filtered'),
        '#url' => Url::fromRoute('native_observability_database_observer.delete_filtered', [], [
          'query' => $request?->query->all() ?? [],
        ]),
        '#attributes' => [
          'class' => ['button', 'button--danger'],
        ],
      ];

      $form['filters']['actions_wrapper']['delete_all'] = [
        '#type' => 'link',
        '#title' => $this->t('Delete ALL'),
        '#url' => Url::fromRoute('native_observability_database_observer.delete_all'),
        '#attributes' => [
          'class' => ['button', 'button--danger'],
        ],
      ];
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $values = $form_state->getValues();

    $query = array_filter([
      'search' => $values['search'] ?? '',
      'relation_type' => $values['relation_type'] ?? '',
      'is_slow' => $values['is_slow'] ?? '',
    ], static fn($value): bool => $value !== '' && $value !== NULL);

    $form_state->setRedirect('native_observability_database_observer.report', [], [
      'query' => $query,
    ]);
  }

}
