<?php

declare(strict_types=1);

namespace Drupal\flowdrop_playground\Form;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\flowdrop_session\Constants\SessionStatus;
use Drupal\flowdrop_workflow\Entity\FlowDropWorkflow;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form to create a session scoped to a workflow.
 *
 * Mounted at /admin/flowdrop/workflows/{flowdrop_workflow}/session/add — the
 * workflow comes from the route, so the form only asks for a session title
 * (prefilled from the workflow label).
 *
 * @internal
 */
final class WorkflowSessionAddForm extends FormBase {

  public function __construct(
    protected readonly EntityTypeManagerInterface $entityTypeManager,
    protected readonly AccountInterface $currentUser,
  ) {}

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

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

  /**
   * {@inheritdoc}
   *
   * @param array $form
   *   The form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param \Drupal\flowdrop_workflow\Entity\FlowDropWorkflow|null $flowdrop_workflow
   *   The workflow upcasted from the route.
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?FlowDropWorkflow $flowdrop_workflow = NULL): array {
    if ($flowdrop_workflow === NULL) {
      throw new NotFoundHttpException();
    }

    $form_state->set('flowdrop_workflow', $flowdrop_workflow);

    $form['workflow'] = [
      '#type' => 'item',
      '#title' => $this->t('Workflow'),
      '#markup' => $flowdrop_workflow->label(),
    ];

    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#default_value' => $flowdrop_workflow->label(),
      '#required' => TRUE,
      '#maxlength' => 255,
      '#description' => $this->t('A human-readable label for this session.'),
    ];

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Create session'),
      '#button_type' => 'primary',
    ];
    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromRoute('flowdrop_playground.workflow.sessions', [
        'flowdrop_workflow' => $flowdrop_workflow->id(),
      ]),
      '#attributes' => ['class' => ['button']],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $workflow = $form_state->get('flowdrop_workflow');
    if (!$workflow instanceof FlowDropWorkflow) {
      throw new \LogicException('Workflow lost between build and submit.');
    }

    $storage = $this->entityTypeManager->getStorage('flowdrop_session');
    /** @var \Drupal\flowdrop_session\Entity\FlowDropSessionInterface $session */
    $session = $storage->create([
      'name' => trim((string) $form_state->getValue('name')),
      'workflow_id' => $workflow->id(),
      'status' => SessionStatus::IDLE,
      'uid' => $this->currentUser->id(),
    ]);
    $session->save();

    $this->messenger()->addStatus($this->t('Created playground session %name.', [
      '%name' => $session->getDisplayLabel(),
    ]));

    $form_state->setRedirect('flowdrop_playground.workflow.session.page', [
      'flowdrop_workflow' => $workflow->id(),
      'flowdrop_session' => $session->id(),
    ]);
  }

}
