<?php

declare(strict_types=1);

namespace Drupal\flowdrop_pipeline\Form;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\flowdrop_pipeline\Constants\PipelineStatus;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Filter form for the pipeline admin list.
 *
 * Submitted via GET so filter state is persisted in the URL and survives
 * page refreshes and bookmarking without server-side session state.
 *
 * @internal
 */
class PipelineFilterForm extends FormBase {

  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static($container->get('entity_type.manager'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, bool $hide_workflow = FALSE): array {
    $request = $this->getRequest();

    // Submit back to the current page so the form works on both the global
    // list and the per-workflow list (which keeps its {flowdrop_workflow}
    // path parameter).
    $route_match = $this->getRouteMatch();
    $current_url = Url::fromRoute(
      $route_match->getRouteName(),
      $route_match->getRawParameters()->all(),
    );

    $form['#method'] = 'get';
    $form['#action'] = $current_url->toString();
    $form['#attributes']['class'][] = 'views-exposed-form';

    $form['filters'] = [
      '#type' => 'container',
      '#attributes' => ['class' => ['form--inline', 'clearfix']],
    ];

    // The Workflow filter is hidden when the list is already scoped to one
    // workflow (the per-workflow pipelines page).
    if (!$hide_workflow) {
      $workflows = $this->entityTypeManager
        ->getStorage('flowdrop_workflow')
        ->loadByProperties(['status' => TRUE]);
      $workflowOptions = ['' => $this->t('- Any workflow -')];
      foreach ($workflows as $workflow) {
        $workflowOptions[$workflow->id()] = $workflow->label();
      }

      $form['filters']['workflow'] = [
        '#type' => 'select',
        '#title' => $this->t('Workflow'),
        '#options' => $workflowOptions,
        '#default_value' => $request->query->get('workflow', ''),
      ];
    }

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

    $form['filters']['date_from'] = [
      '#type' => 'date',
      '#title' => $this->t('Created from'),
      '#default_value' => $request->query->get('date_from', ''),
    ];

    $form['filters']['date_to'] = [
      '#type' => 'date',
      '#title' => $this->t('Created to'),
      '#default_value' => $request->query->get('date_to', ''),
    ];

    $form['filters']['actions'] = [
      '#type' => 'actions',
    ];

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

    $form['filters']['actions']['reset'] = [
      '#type' => 'link',
      '#title' => $this->t('Reset'),
      '#url' => $current_url,
      '#attributes' => ['class' => ['button']],
    ];

    // Remove Drupal's hidden form fields so they don't pollute the URL.
    $form['form_build_id']['#access'] = FALSE;
    $form['form_token']['#access'] = FALSE;
    $form['form_id']['#access'] = FALSE;

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    // GET forms redirect automatically via the browser — no server-side
    // redirect needed.
  }

}
