<?php

declare(strict_types=1);

namespace Drupal\native_observability_cache_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 cache observer raw listing.
 */
final class CacheObserverFiltersForm extends FormBase {

  /**
   * Creates a new cache observer filters form instance.
   */
  public function __construct(
    private readonly RequestStack $cacheObserverRequestStack,
    private readonly AccountProxyInterface $cacheObserverCurrentUser,
  ) {
  }

  /**
   * {@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_cache_observer_filters_form';
  }

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

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

    $eventTypes = ['response_cache', 'cacheability', 'tag_invalidation'];
    $eventTypeOptions = array_combine($eventTypes, $eventTypes) ?: [];

    $cacheStatuses = [
      'HIT', 'MISS', 'UNCACHEABLE', 'CACHEABLE', 'INVALIDATED', 'UNKNOWN',
    ];
    $cacheStatusOptions = array_combine($cacheStatuses, $cacheStatuses) ?: [];

    $httpMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
    $httpMethodOptions = array_combine($httpMethods, $httpMethods) ?: [];

    $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('Path, route, request ID...'),
      ],
    ];

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

    $form['filters']['event_type_wrapper']['event_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Event type'),
      '#options' => ['' => $this->t('- Any -')] + $eventTypeOptions,
      '#default_value' => $request?->query->get('event_type', ''),
    ];

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

    $form['filters']['status_wrapper']['status'] = [
      '#type' => 'select',
      '#title' => $this->t('Status'),
      '#options' => ['' => $this->t('- Any -')] + $cacheStatusOptions,
      '#default_value' => $request?->query->get('status', ''),
    ];

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

    $form['filters']['method_wrapper']['method'] = [
      '#type' => 'select',
      '#title' => $this->t('Method'),
      '#options' => ['' => $this->t('- Any -')] + $httpMethodOptions,
      '#default_value' => $request?->query->get('method', ''),
    ];

    $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_cache_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_cache_observer.export_filtered', [], [
        'query' => $request?->query->all() ?? [],
      ]),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];

    if ($this->cacheObserverCurrentUser->hasPermission('administer native observability cache observer')) {
      $form['filters']['actions_wrapper']['delete_filtered'] = [
        '#type' => 'link',
        '#title' => $this->t('Delete filtered'),
        '#url' => Url::fromRoute('native_observability_cache_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_cache_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'] ?? '',
      'event_type' => $values['event_type'] ?? '',
      'status' => $values['status'] ?? '',
      'method' => $values['method'] ?? '',
    ], static fn($value): bool => $value !== '' && $value !== NULL);

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

}
