<?php

namespace Drupal\keycloak_user_provisioning\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\keycloak_user_provisioning\MoKeycloakSupport;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form for requesting a trial of Keycloak user provisioning premium features.
 */
class MoKeycloakRequestTrial extends FormBase {
  use StringTranslationTrait;
  /**
   * ImmutableConfig property.
   *
   * @var Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

  /**
   * Messenger property.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a new MoKeycloakRequestTrial object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MessengerInterface $messenger, AccountProxyInterface $current_user) {
    $this->configFactory = $config_factory;
    $this->config = $config_factory->get('user_provisioning.settings');
    $this->messenger = $messenger;
    $this->currentUser = $current_user;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mo_keycloak_request_trial';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Attach necessary libraries for AJAX and dialog functionality.
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $form['#attached']['library'][] = 'keycloak_user_provisioning/keycloak_user_provisioning.admin';

    // Container wrapper for the form with ID for AJAX replacement.
    $form['miniorange_keycloak_support'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'modal_request_trial_form',
      ],
    ];

    // Status messages for displaying form errors/success.
    $form['miniorange_keycloak_support']['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];

    // Trial request information.
    $form['miniorange_keycloak_support']['mo_keycloak_trial_info'] = [
      '#markup' => '<div class="trial-request-info">
                          <p>' . $this->t('Get access to all premium features of Keycloak User Provisioning for 7 days.') . '</p>
                      </div>',
    ];

    // Email field.
    $form['miniorange_keycloak_support']['mo_keycloak_trial_email_address'] = [
      '#type' => 'email',
      '#title' => $this->t('Email'),
      '#required' => TRUE,
      '#default_value' => $this->currentUser->getEmail(),
      '#attributes' => ['placeholder' => $this->t('Enter your email'), 'style' => 'width:99%;margin-bottom:1%;'],
    ];

    // Trial method select field.
    $form['miniorange_keycloak_support']['mo_keycloak_trial_method'] = [
      '#type' => 'select',
      '#title' => $this->t('Trial Method'),
      '#attributes' => ['style' => 'width:99%;height:30px;margin-bottom:1%;'],
      '#options' => [
        'Drupal to Keycloak CRUD operations' => $this->t('Drupal to Keycloak Sync (Complete CRUD operations)'),
        'Keycloak to Drupal CRUD operations' => $this->t('Keycloak to Drupal Sync (Complete CRUD operations)'),
        'bidirectional' => $this->t('Bidirectional sync (From Keycloak to Drupal or vice versa)'),
        'Not Sure' => $this->t('Not Sure (We will assist you further)'),
      ],
    ];

    // Description textarea.
    $form['miniorange_keycloak_support']['mo_keycloak_trial_description'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Description'),
      '#required' => FALSE,
      '#attributes' => ['placeholder' => $this->t('Describe your use case here!'), 'style' => 'width:99%;'],
      '#rows' => 3,
    ];

    // Form actions.
    $form['miniorange_keycloak_support']['actions'] = [
      '#type' => 'actions',
    ];

    // Submit button with AJAX.
    $form['miniorange_keycloak_support']['actions']['mo_keycloak_trial_email_send'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#attributes' => [
        'class' => [
          'use-ajax',
          'button--primary',
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

    return $form;
  }

  /**
   * AJAX callback for submitting the trial request form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The AJAX response.
   */
  public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();

    $response = new AjaxResponse();
    $email = $form_values['mo_keycloak_trial_email_address'] ?? '';
    
    if ($form_state->hasAnyErrors()) {
      // Rebuild the form to show validation errors.
      $response->addCommand(new ReplaceCommand('#modal_request_trial_form', $form['miniorange_keycloak_support']));
    }
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $this->messenger->addError($this->t('The email address <b><i>@email</i></b> is not valid.', ['@email' => $email]));
      // Rebuild the form to show the error message.
      $response->addCommand(new ReplaceCommand('#modal_request_trial_form', $form['miniorange_keycloak_support']));
    }
    else {
      $query = $form_values['mo_keycloak_trial_method'] ?? '';
      $query_description = $form_values['mo_keycloak_trial_description'] ?? '';
      $query_type = 'Trial Request';

      $support = new MoKeycloakSupport($email, $query, $query_description, $query_type);
      $support_response = $support->sendSupportQuery();

      if ($support_response) {
        $this->messenger->addStatus($this->t('Support query successfully sent. We will provide you with a trial very shortly.'));
      }
      else {
        $email_link = Markup::create('<a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a>');
        $this->messenger->addError($this->t('Error submitting the support query. Please send us your query at @email.', [
          '@email' => $email_link,
        ]));
      }
      // Close the modal and redirect.
      $response->addCommand(new RedirectCommand(Url::fromRoute('keycloak_user_provisioning.overview')->toString()));
    }
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}
