<?php

namespace Drupal\keycloak_user_provisioning\Form;

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\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Form for Keycloak to Drupal user provisioning configuration.
 */
class MoKeycloakToDrupal extends FormBase {
  use StringTranslationTrait;
  /**
   * Base URL of the site.
   *
   * @var string
   */
  private $baseUrl;

  /**
   * ImmutableConfig property.
   *
   * @var Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

  /**
   * Config property.
   *
   * @var \Drupal\Core\Config\ConfigInterface
   */
  protected $configFactory;

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

  /**
   * Constructs a new MoKeycloakToDrupal object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MessengerInterface $messenger, RequestStack $request_stack) {
    $base_url = $request_stack->getCurrentRequest()->getSchemeAndHttpHost();
    $this->baseUrl = $base_url;
    $this->config = $config_factory->get('keycloak_user_provisioning.settings');
    $this->configFactory = $config_factory->getEditable('keycloak_user_provisioning.settings');
    $this->messenger = $messenger;
  }

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

  /**
   * FormID of the form.
   *
   * @return string
   *   Returns formID of the form.
   */
  public function getFormId() {
    return 'MoKeycloakToDrupal';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['mo_keycloak_sync_add_css'] = [
      '#attached' => [
        'library' => [
          'keycloak_user_provisioning/keycloak_user_provisioning.admin',
        ],
      ],
    ];

    $this->configFactory->set('keycloak_user_provisioning_status1', 'keycloak_to_drupal')->save();

    // Create vertical tabs container.
    $form['keycloak_tabs'] = [
      '#type' => 'vertical_tabs',
      '#attributes' => ['class' => ['mo-keycloak-vertical-tabs']],
    ];

    // Add the three main sections as vertical tabs.
    $this->keycloakManualDrupalProvisioning($form, $form_state);
    $this->schedulerBasedProvisioning($form, $form_state);
    $this->additionalFeatures($form, $form_state);

    return $form;
  }

  /**
   * Builds manual provisioning configuration form elements.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function keycloakManualDrupalProvisioning(array &$form, FormStateInterface $form_state): array {
    $form['mo_keycloak_provisioning_details'] = [
      '#type' => 'details',
      '#title' => Markup::create($this->t('Manual Provisioning Configuration')),
      '#group' => 'keycloak_tabs',
      '#collapsible' => TRUE,
      '#attributes' => ['class' => ['field_set_label_css'], 'markup' => TRUE],
    ];

    $premium_badge = ' <span class="premium-badge">PREMIUM</span>';
    $form['mo_keycloak_provisioning_details']['fieldset'] = [
      '#type' => 'fieldset',
      '#title' => Markup::create($this->t('Configure user provisioning settings manually between Drupal and Keycloak.') . $premium_badge),
    ];

    $this->moProvisioningOperations($form, 'mo_keycloak_provisioning_details');

    $form['mo_keycloak_provisioning_details']['fieldset']['create_user_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Sync Users'),
      '#attributes' => ['style' => 'box-shadow: none'],
    ];

    $form['mo_keycloak_provisioning_details']['fieldset']['create_user_fieldset']['mo_keycloak_drupal_username'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#attributes' => ['placeholder' => 'Search keycloak username of user to sync'],
      '#disabled' => TRUE,
      '#prefix' => '<p class="mo_keycloak_highlight_background"><strong>Note:</strong> Search the username of user present in keycloak to sync it to the Drupal.</p><div class="container-inline">',
    ];

    $form['mo_keycloak_provisioning_details']['fieldset']['create_user_fieldset']['mo_keycloak_sync_all_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Sync All Users'),
      '#button_type' => 'primary',
      '#attributes' => ['class' => ['mo_keycloak_sync_all_button']],
      '#disabled' => TRUE,
    ];

    $form['mo_keycloak_provisioning_details']['keycloak_to_drupal_save_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save Settings'),
      '#button_type' => 'primary',
      '#disabled' => TRUE,
    ];

    return $form;
  }

  /**
   * Builds provisioning operations checkboxes.
   *
   * @param array $form
   *   The form array.
   * @param string $field_set
   *   The fieldset name.
   */
  public function moProvisioningOperations(array &$form, $field_set) {
    $form[$field_set]['fieldset']['read_user_keycloak'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Read user'),
      '#disabled' => TRUE,
      '#prefix' => '<div class="keycloak_sync_checkboxes">',
    ];

    $form[$field_set]['fieldset']['create_user_keycloak'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Create user'),
      '#disabled' => TRUE,
    ];

    $form[$field_set]['fieldset']['update_user_keycloak'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Update user'),
      '#disabled' => TRUE,
    ];

    $form[$field_set]['fieldset']['deactivate_user_keycloak'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Deactivate user'),
      '#disabled' => TRUE,
    ];

    $form[$field_set]['fieldset']['delete_user_keycloak'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Delete user'),
      '#disabled' => TRUE,
      '#suffix' => '</div>',
    ];
  }

  /**
   * Builds scheduler-based provisioning configuration form elements.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function schedulerBasedProvisioning(array &$form, FormStateInterface $form_state) {
    $form['mo_keycloak_scheduler_provisioning_details'] = [
      '#type' => 'details',
      '#title' => $this->t('Scheduler Based Provisioning Configuration'),
      '#group' => 'keycloak_tabs',
      '#collapsible' => TRUE,
      '#attributes' => ['class' => ['field_set_label_css']],
    ];

    $premium_badge = ' <span class="premium-badge">PREMIUM</span>';
    $form['mo_keycloak_scheduler_provisioning_details']['fieldset'] = [
      '#type' => 'fieldset',
      '#title' => Markup::create($this->t('Configure automated user provisioning between Drupal and Keycloak at scheduled intervals.') . $premium_badge),
    ];

    $this->moProvisioningOperations($form, 'mo_keycloak_scheduler_provisioning_details');

    $form['mo_keycloak_scheduler_provisioning_details']['fieldset']['mo_keycloak_scheduler_provisioning_configuration'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Configuration'),
      '#attributes' => ['style' => 'box-shadow: none'],
    ];

    $form['mo_keycloak_scheduler_provisioning_details']['fieldset']['mo_keycloak_scheduler_provisioning_configuration']['auto_creation'] = [
      '#type' => 'number',
      '#title' => $this->t('Fetch All users details in next * minutes'),
      '#attributes' => ['style' => 'width: 45%'],
      '#disabled' => TRUE,

    ];

    $form['mo_keycloak_scheduler_provisioning_details']['keycloak_to_drupal_save_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save Settings'),
      '#button_type' => 'primary',
      '#disabled' => TRUE,
    ];

    return $form;
  }

  /**
   * Builds additional features configuration form elements.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function additionalFeatures(array &$form, FormStateInterface $form_state) {
    $form['mo_keycloak_features_details'] = [
      '#type' => 'details',
      '#title' => $this->t('Additional Features'),
      '#group' => 'keycloak_tabs',
      '#collapsible' => TRUE,
      '#attributes' => ['class' => ['field_set_label_css', 'container-inline']],
    ];

    $premium_badge = ' <span class="premium-badge">PREMIUM</span>';
    $form['mo_keycloak_features_details']['mo_keycloak_perform_action_on delete'] = [
      '#title' => Markup::create($this->t('Perform the following action on Drupal user list when user is deleted from IDP:') . $premium_badge),
      '#type' => 'radios',
      '#tree' => TRUE,
      '#options' => [
        'NONE' => $this->t('Do Nothing'),
        'DELETE' => $this->t('Delete Users'),
        'DEACTIVATE' => $this->t('Deactivate Users'),
        'ANONYMOUS' => $this->t('Delete user and assign content to an anonymous user'),
      ],
      '#disabled' => TRUE,
    ];

    $form['mo_keycloak_features_details']['keycloak_to_drupal_save_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save Settings'),
      '#button_type' => 'primary',
      '#disabled' => TRUE,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Handle form submission.
    $this->messenger->addMessage($this->t('Configuration has been saved.'));
  }

}
