<?php

namespace Drupal\keycloak_user_provisioning\Form;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Extension\ModuleExtensionList;
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 Drupal\Core\Url;
use Drupal\keycloak_user_provisioning\Helper\MoKeycloakHelper;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;

/**
 * Form for Keycloak overview and configuration.
 */
class MoKeycloakOverview extends FormBase {
  use StringTranslationTrait;
  /**
   * Base URL of the site.
   *
   * @var string
   */
  private string $baseUrl;

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

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

  /**
   * URL Path property.
   *
   * @var string
   */
  private $urlPath;

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

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

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * The extension list module service.
   *
   * @var \Drupal\Core\Extension\ModuleExtensionList
   */
  protected $moduleExtensionList;

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

  /**
   * The mo keycloak helper.
   *
   * @var \Drupal\keycloak_user_provisioning\Helper\MoKeycloakHelper
   */
  private MoKeycloakHelper $moKeycloakHelper;

  /**
   * Constructs a new MoKeycloakOverview 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.
   * @param \Drupal\Core\Extension\ModuleExtensionList $module_extension_list
   *   The module extension list service.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\keycloak_user_provisioning\Helper\MoKeycloakHelper $moKeycloakHelper
   *   The Keycloak helper service.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    MessengerInterface $messenger,
    RequestStack $request_stack,
    ModuleExtensionList $module_extension_list,
    AccountProxyInterface $current_user,
    MoKeycloakHelper $moKeycloakHelper,
  ) {
    $base_url = $request_stack->getCurrentRequest()->getSchemeAndHttpHost();
    $this->baseUrl = $base_url;
    $this->configFactoryService = $config_factory;
    $this->config = $config_factory->get('keycloak_user_provisioning.settings');
    $this->configFactory = $config_factory->getEditable('keycloak_user_provisioning.settings');
    $this->messenger = $messenger;
    $this->requestStack = $request_stack;
    $this->moduleExtensionList = $module_extension_list;
    $this->currentUser = $current_user;
    $this->urlPath = $base_url . '/' . $module_extension_list->getPath('keycloak_user_provisioning') . '/includes';
    $this->moKeycloakHelper = $moKeycloakHelper;
  }

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

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

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

    $request = $this->requestStack->getCurrentRequest();
    $tab = $request ? $request->query->get('tab') : NULL;

    if (!$tab) {
      $last_step = $this->configFactory->get('keycloak_user_provisioning_status1');
      $start_step = $this->configFactory->get('keycloak_user_provisioning_status');
      if (($last_step == 'overview' || $last_step == NULL) || $start_step == 'overview') {
        $this->keycloakSyncOverview($form, $form_state);
      }
      else {
        if ($last_step == 'overview?tab=drupal-to-keycloak-configuration') {
          $this->step1Configuration($form, $form_state);
        }
        elseif ($last_step == 'overview?tab=how-to-perform-sync') {
          $this->step2SyncOption($form, $form_state);
        }
        elseif ($last_step == 'overview?tab=provisioning-configuration') {
          $this->step3TypesOfProvisioning($form, $form_state);
        }
        elseif ($last_step == 'keycloak_to_drupal') {
          $response = new RedirectResponse(Url::fromRoute('keycloak_user_provisioning.mo_keycloak_to_drupal')->toString());
          $response->send();
          return new Response();
        }
        elseif ($last_step == 'mo_drupal_to_keycloak') {
          $response = new RedirectResponse(Url::fromRoute('keycloak_user_provisioning.mo_drupal_to_keycloak')->toString());
          $response->send();
          return new Response();
        }
        elseif ($last_step == 'mo_mapping_tab') {
          $response = new RedirectResponse(Url::fromRoute('keycloak_user_provisioning.mo_mapping_tab')->toString());
          $response->send();
          return new Response();
        }
        elseif ($last_step == 'MoKeycloakAuditLogs') {
          $response = new RedirectResponse(Url::fromRoute('keycloak_user_provisioning.keycloak_audit_logs')->toString());
          $response->send();
          return new Response();
        }
      }
    }
    else {
      if ($tab == 'drupal-to-keycloak-configuration') {
        $this->step1Configuration($form, $form_state);
      }
      elseif ($tab == 'how-to-perform-sync') {
        $this->step2SyncOption($form, $form_state);
      }
      elseif ($tab == 'provisioning-configuration') {
        $this->step3TypesOfProvisioning($form, $form_state);
      }
    }

    return $form;
  }

  /**
   * Builds the Keycloak sync overview form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_statte
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function keycloakSyncOverview(array &$form, FormStateInterface $form_statte) {
    $this->configFactory->set('keycloak_user_provisioning_status1', 'overview')->save();
    $this->configFactory->set('keycloak_user_provisioning_status', 'overview')->save();

    $form['overview_header_style'] = [
      '#markup' => '<div class="mo_keycloak_header_container">',
    ];

    $current_logged_in_user = $this->currentUser->getDisplayName();
    $current_logged_in_user = !empty($current_logged_in_user) ? $current_logged_in_user : 'there';

    $module_name = Markup::create('<strong>' . $this->t('Keycloak User Provisioning and Management') . '</strong>');
    $email_link = Markup::create('<a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a>');
    $form['overview_left_side_content'] = [
      '#markup' =>
      '<div class="mo_keycloak_header_container_left">
                            <h3>' . $this->t("Let's Get Started!") . '</h3>
                            <p>' . $this->t('Hello @user, Thank you for installing @module module!', [
                              '@user' => $current_logged_in_user,
                              '@module' => $module_name,
                            ]) . '<br><br>' . $this->t('This Module provides you a bidirectional user synchronization and provisioning between the Keycloak and your Drupal site. The module supports User Provisioning from both Drupal to Keycloak as well as Keycloak to Drupal.') .
      '<br><br>' . $this->t('Feel free to contact us at @email if you need any sort of assistance during the setup.', [
        '@email' => $email_link,
      ]) . '</p>',
    ];

    $referer = "https://plugins.miniorange.com/drupal-keycloak-user-provisioning";

    $form['overview_left_side_guide_button'] = [
      '#type' => 'link',
      '#title' => $this->t('&#128366; Setup Guide'),
      '#url' => Url::fromUri($referer),
      '#attributes' => ['class' => ['button', 'button--primary'], 'target' => '_blank'],
      '#prefix' => '<div class="container-inline">',
    ];

    $form['overview_left_side_configure-button'] = [
      '#type' => 'submit',
      '#value' => $this->t("&#9881; &nbsp; Let's configure the module &nbsp; &#11166;"),
      '#button_type' => 'primary',
      '#submit' => ["::letsConfigureButton"],
      '#prefix' => '&nbsp;&nbsp;&nbsp;',
      '#suffix' => '</div>',
    ];

    $form['overview_left_side_content_end'] = [
      '#markup' => '</div>',
    ];

    $form['overview_right_side_content'] = [
      '#markup' => $this->t(
              '<div class="mo_keycloak_header_container_right"><div> <a href="https://plugins.miniorange.com/drupal-keycloak-user-sync"  target="_blank" >
                  <img class="mo_keycloak_header_container_right_video" src="@url" alt="setup_video_image"> </a>
                  </div>',
              ['@url' => $this->urlPath . '/video_thumbnil.png']
      ),
    ];

    return $form;
  }

  /**
   * For redirecting user to drupal to keycloak configuration page.
   */
  public function letsConfigureButton(array &$form, FormStateInterface $form_state) {
    $this->configFactory->set('keycloak_user_provisioning_status', 'overview?tab=drupal-to-keycloak-configuration')->save();
    $url = Url::fromRoute('keycloak_user_provisioning.overview', [], ['query' => ['tab' => 'drupal-to-keycloak-configuration']]);
    $form_state->setRedirectUrl($url);
  }

  /**
   * Builds step 1 configuration form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function step1Configuration(array &$form, FormStateInterface $form_state): array {
    $this->configFactory->set('keycloak_user_provisioning_status', 'drupal-to-keycloak-configuration')->save();
    $this->configFactory->set('keycloak_user_provisioning_status1', 'overview?tab=drupal-to-keycloak-configuration')->save();

    $form['header_step1_guide_button'] = [
      '#markup' => '<div class="container-inline"><a class="button button--primary mo-guides-floating" target="_blank" href="https://plugins.miniorange.com/drupal-keycloak-user-sync">🕮 Setup guide</a></div>',
    ];

    $form['header_top_style2'] = [
      '#markup' => '<h2><u>' . $this->t('STEP 1/3') . '</u></h2><br><h3>' . $this->t('Keycloak App Configuration') . '</h3><hr><br><div class="mo_keycloak_highlight_background"><p>' . $this->t('Configure the following settings to register your Keycloak application in Drupal.') . '</p></div>',
    ];

    $this->keycloakConfiguration($form, $form_state, 'configuration');

    $form['configure_keycloak_back_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('&#11164; Back'),
      '#button_type' => 'danger',
      '#limit_validation_errors' => [],
      '#submit' => ["::backFun"],
      '#prefix' => '<div class="mo-table-button-center">',
    ];

    $form['configure_keycloak_test_button1'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save and Test Configuration'),
      '#button_type' => 'primary',
      '#submit' => ['::saveAndTestConfigureKeycloak'],
    ];

    if ($this->config->get('mo_keycloak_attr_list_from_server') != '') {
      $keycloak_test_data = Json::decode($this->config->get('mo_keycloak_attr_list_from_server'));
    }

    if (isset($keycloak_test_data['id'])) {
      $form['configure_keycloak_manual_sync_test'] = [
        '#type' => 'link',
        '#title' => $this->t('Test Manual Sync'),
        '#url' => Url::fromRoute('keycloak_user_provisioning.testManualSync'),
        '#attributes' => [
          'class' => ['button', 'button--primary', 'use-ajax', 'js-form-submit', 'form-submit'],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => json_encode(['width' => '65%']),
        ],
      ];
    }

    if (isset($keycloak_test_data['id']) || isset($keycloak_test_data['error'])) {
      $form['configure_keycloak_next_button'] = [
        '#type' => 'submit',
        '#value' => $this->t("Next &#11166;"),
        '#button_type' => 'primary',
        '#attributes' => ['style' => 'float:right'],
        '#disabled' => isset($keycloak_test_data['error']),
        '#submit' => ["::nextBtnFun"],
      ];
    }

    $this->testConfigurationResult($form, $form_state);

    return $form;
  }

  /**
   * Builds Keycloak configuration form elements.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param string $status
   *   The status (configuration or summary).
   *
   * @return array
   *   The form array.
   */
  public function keycloakConfiguration(array &$form, FormStateInterface $form_state, $status = ''):array {
    if ($status == 'configuration') {
      $this->keycloakConfigurationStatus($form, $form_state, 'configuration');
    }
    elseif ($status == 'summary') {
      $this->keycloakConfigurationStatus($form, $form_state, 'summary');
    }
    return $form;
  }

  /**
   * Builds Keycloak configuration status form elements.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param string $status
   *   The status (configuration or summary).
   */
  public function keycloakConfigurationStatus(array &$form, FormStateInterface $form_state, $status = ''): void {
    $form['keycloak_user_provisioning_' . $status . '_base_url'] = [
      '#type' => 'url',
      '#title' => $this->t('Keycloak Domain:'),
      '#description' => $this->t('Enter the base URL of your Keycloak server (e.g., https://keycloak.example.com)'),
      '#default_value' => $this->configFactory->get('keycloak_user_provisioning_base_url'),
      '#required' => TRUE,
    ];

    $form['keycloak_user_provisioning_' . $status . '_client_id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Client ID:'),
      '#description' => $this->t('Enter the client ID for authentication'),
      '#default_value' => $this->configFactory->get('keycloak_user_provisioning_client_id'),
      '#required' => TRUE,
    ];

    $form['keycloak_user_provisioning_' . $status . '_client_secret'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Client Secret:'),
      '#description' => $this->t('Enter the client Secret'),
      '#default_value' => $this->configFactory->get('keycloak_user_provisioning_client_secret'),
      '#required' => TRUE,
    ];

    $form['keycloak_user_provisioning_' . $status . '_realm'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Keycloak Realm:'),
      '#description' => $this->t('Enter the Keycloak Realm'),
      '#default_value' => $this->configFactory->get('keycloak_user_provisioning_realm'),
      '#required' => TRUE,
    ];
  }

  /**
   * For returning to overview page.
   */
  public function backFun(array &$form, FormStateInterface $form_state) {
    $this->configFactory->set('keycloak_user_provisioning_status1', 'overview')->save();
    $url = Url::fromRoute('keycloak_user_provisioning.overview');
    $form_state->setRedirectUrl($url);
  }

  /**
   * Saves and tests Keycloak configuration.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function saveAndTestConfigureKeycloak(array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();

    $data = [
      'keycloak_user_provisioning_configuration_base_url' => 'keycloak_user_provisioning_base_url',
      'keycloak_user_provisioning_configuration_client_id' => 'keycloak_user_provisioning_client_id',
      'keycloak_user_provisioning_configuration_client_secret' => 'keycloak_user_provisioning_client_secret',
      'keycloak_user_provisioning_configuration_realm' => 'keycloak_user_provisioning_realm',
    ];

    foreach ($data as $key => $value) {
      $this->configFactory->set($value, $form_values[$key])->save();
    }

    $this->configFactoryService->getEditable('user_provisioning.settings')->set('mo_user_provisioning_configured_application', 'keycloak')->save();

    $this->moKeycloakHelper->fetchAttributes();

    $keycloak_test_data = Json::decode($this->config->get('mo_keycloak_attr_list_from_server'));
    if ($keycloak_test_data != '') {
      if (isset($keycloak_test_data["error"])) {
        $test_result_link = Markup::create('<a href="#test_config_result">Test Configuration Result</a>');
        $this->messenger->addError($this->t('An error occurred while performing test configuration. Please refer to @link for more information.', [
          '@link' => $test_result_link,
        ]));
      }
      else {
        $here_link = Markup::create('<a href="#test_config_result">HERE</a>');
        $this->messenger->addStatus($this->t('Test Configuration successful. You can check the complete list of attributes received from Keycloak by clicking on the link @link.', [
          '@link' => $here_link,
        ]));
      }
    }

  }

  /**
   * Displays test configuration result.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function testConfigurationResult(array &$form, FormStateInterface $form_state) {
    $keycloak_test_data = NULL;
    if ($this->config->get('mo_keycloak_attr_list_from_server') != NULL) {
      $keycloak_test_data = Json::decode($this->config->get('mo_keycloak_attr_list_from_server'));
    }

    if ($keycloak_test_data != NULL) {
      $form['keycloak_configuration_display_test_data'] = [
        '#type' => 'details',
        '#title' => $this->t('Test Configuration Result'),
        '#open' => isset($keycloak_test_data["error"]),
        '#prefix' => '<div id="test_config_result">',
        '#suffix' => '</div>',
      ];

      $form['keycloak_configuration_display_test_data']['header_message'] = [
        '#markup' => isset($keycloak_test_data['error'])
          ? Markup::create(
                    '<div style="font-family: Calibre, serif; padding: 0 3%;">'
                    . '<div style="color: #a94442; background-color: #f2dede; padding: 15px; margin-bottom: 20px; text-align: center; border: 1px solid #E6B3B2; font-size: 18pt;">ERROR</div>'
                    . '<div style="color: #a94442; font-size: 14pt; margin-bottom: 20px;">Error Details:</div>'
                    . '</div>'
        )
          : Markup::create(
                    '<div class="success-container">'
                    . '<div class="mo-success-message" style="color: #3c763d; background-color: #dff0d8; padding: 15px; margin-bottom: 20px; text-align: center; border: 1px solid #AEDB9A; font-size: 18pt;">SUCCESS</div>'
                    . '</div>'
        ),
      ];

      $form['keycloak_configuration_display_test_data']['keycloak_configuration_show_test_data'] = [
        '#type' => 'table',
        '#responsive' => TRUE,
        '#attributes' => ['style' => 'border-collapse: separate;', 'class' => ['mo_keycloak_attributes_table']],
      ];

      foreach ($keycloak_test_data as $key => $value) {
        $row = $this->keycloakTestConfigurationData($key, $value);
        $form['keycloak_configuration_display_test_data']['keycloak_configuration_show_test_data'][$key] = $row;
      }
    }
  }

  /**
   * Shows test configuration result.
   *
   * @return array
   *   Returns array of form elements.
   */
  public function keycloakTestConfigurationData($key, $value): array {
    $row[$key] = [
      '#type' => 'item',
      '#plain_text' => $key,
    ];

    $row[$value] = [
      '#type' => 'item',
      '#plain_text' => $value,
    ];
    return $row;
  }

  /**
   * For redirecting user to how to perform sync page.
   */
  public function nextBtnFun(array &$form, FormStateInterface $form_state) {
    $this->configFactory->set('keycloak_user_provisioning_status', 'how-to-perform-sync')->save();
    $url = Url::fromRoute('keycloak_user_provisioning.overview', [], ['query' => ['tab' => 'how-to-perform-sync']]);
    $form_state->setRedirectUrl($url);
  }

  /**
   * Builds step 2 sync option form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function step2SyncOption(array &$form, FormStateInterface $form_state): array {
    $this->configFactory->set('keycloak_user_provisioning_status1', 'overview?tab=how-to-perform-sync')->save();

    $form['header_setup_guide_button_provisioning_type'] = [
      '#markup' => '<div class="container-inline"><a class="button button--primary mo-guides-floating" target="_blank" href= "https://plugins.miniorange.com/drupal-keycloak-user-sync">🕮 Setup guide</a></div> ',
    ];

    $form['header_top_style_provisioning_type'] = [
      '#markup' => '<h2><u>' . $this->t('STEP 2/3') . '</u></h2><br><h3 class="mo_keycloak_text_center">' . $this->t('Please select how would you like to perform the synchronization') . '</h3><br>',
    ];

    $this->configFactory->set('keycloak_user_provisioning_status', 'how-to-perform-sync')->save();

    $rows = [
          [
            Markup::create('<a href="' . $this->baseUrl . '/admin/config/people/keycloak_user_provisioning/overview?tab=provisioning-configuration"><div class="mo_keycloak_step_1_img mo_keycloak_text_center"><img class="mo_keycloak_sync_gif" src="' . $this->urlPath . '/Drupal_to_Keycloak.png" alt="drupal_to_keycloak"></div></a>'),
            Markup::create('<a class="js-form-submit form-submit use-ajax mo_top_bar_button" data-dialog-type="modal" data-dialog-options="{&quot;width&quot;:&quot;40%&quot;}" href="requestTrialKeycloak"><div class="mo_keycloak_step_1_img mo_keycloak_text_center"><img class="mo_keycloak_sync_gif" src="' . $this->urlPath . '/Keycloak_to_Drupal.png" alt="keycloak_to_drupal"></div></a>'),
          ],
    ];

    $form['keycloak_sync_how_to_sync'] = [
      '#type' => 'table',
      '#responsive' => TRUE,
      '#rows' => $rows,
      '#attributes' => ['style' => 'border-collapse: separate;', 'class' => ['step1_how_to_sync']],
    ];

    $form['keycloak_sync_back_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('&#11164; Back'),
      '#button_type' => 'danger',
      '#submit' => ["::backBtnHowToSync"],
    ];

    return $form;
  }

  /**
   * Redirects back to how to sync page.
   */
  public function backBtnHowToSync(array &$form, FormStateInterface $form_state) {
    $this->configFactory->set('keycloak_user_provisioning_status', 'drupal-to-keycloak-configuration')->save();
    $url = Url::fromRoute('keycloak_user_provisioning.overview', [], ['query' => ['tab' => 'drupal-to-keycloak-configuration']]);
    $form_state->setRedirectUrl($url);
  }

  /**
   * Builds step 3 types of provisioning form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The form array.
   */
  public function step3TypesOfProvisioning(array &$form, FormStateInterface $form_state):array {
    $this->configFactory->set('keycloak_user_provisioning_status', 'provisioning-configuration')->save();
    $this->configFactory->set('keycloak_user_provisioning_status1', 'overview?tab=provisioning-configuration')->save();

    $form['header_setup_guide_button_provisioning_type'] = [
      '#markup' => '<div class="container-inline"><a class="button button--primary mo-guides-floating" target="_blank" href="https://plugins.miniorange.com/drupal-keycloak-user-sync">🕮 Setup guide</a></div> ',
    ];

    $form['header_top_style_provisioning_type'] = [
      '#markup' => '<h2><u>' . $this->t('STEP 3/3') . '</u></h2><br><h3>' . $this->t('Types of Provisioning') . '</h3><hr><br>',
    ];

    $form['mo_keycloak_provisioning_type_table'] = [
      '#type' => 'table',
      '#responsive' => TRUE,
      '#attributes' => ['class' => ['mo_keycloak_provisioning_types']],
    ];

    $row = $this->moTableDataProvisioningType();
    $form['mo_keycloak_provisioning_type_table'][] = $row;

    $form['configure_keycloak_back_button'] = [
      '#type' => 'submit',
      '#value' => $this->t('&#11164; Back'),
      '#button_type' => 'danger',
      '#submit' => ["::backBtnProvisioningType"],
      '#prefix' => '<div class="mo-table-button-center">',
    ];

    $form['configure_keycloak_next_button'] = [
      '#type' => 'submit',
      '#value' => $this->t("All done!!"),
      '#button_type' => 'primary',
      '#submit' => ["::performSyncFunction"],
      '#attributes' => ['style' => 'float:right'],
    ];

    return $form;
  }

  /**
   * Builds table data for provisioning types.
   *
   * @return array
   *   Returns array of form elements.
   */
  public function moTableDataProvisioningType(): array {
    $row['keycloak_sync_manual_provisioning_button'] = [
      '#type' => 'link',
      '#title' => $this->t('&#9881; Configure'),
      '#url' => Url::fromRoute('keycloak_user_provisioning.manualConfiguration'),
      '#attributes' => [
        'style' => ['margin-left:33%'],
        'class' => ['button', 'button--primary', 'use-ajax', 'js-form-submit', 'form-submit'],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => json_encode(['width' => 'auto']),
      ],
      '#prefix' => '<div class="mo_keycloak_sync_text_center"><h4>' . $this->t('Manual/On-Demand Provisioning') . '</h4></div><hr>' . $this->t('In this method users can be manually provisioned to Keycloak whenever it required.') . '<br>' . $this->t('It allows provisioning of the single user as well as sync all the existing user in the Drupal.') . '<br><br>',
    ];

    $row['keycloak_sync_automatic_provisioning_button'] = [
      '#type' => 'link',
      '#title' => $this->t('&#9881; Configure'),
      '#url' => Url::fromRoute('keycloak_user_provisioning.automaticConfiguration'),
      '#attributes' => [
        'style' => ['margin-left:33%'],
        'class' => ['button', 'button--primary', 'use-ajax', 'js-form-submit', 'form-submit'],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => json_encode(['width' => '65%']),
      ],
      '#prefix' => '<div class="mo_keycloak_sync_text_center"><h4>' . $this->t('Automatic/Real-time Provisioning') . '</h4></div><hr>' . $this->t('This methods allows the real-time synchronization of the users form Drupal to Keycloak.') . '<br>' . $this->t('Users are provisioned to Keycloak as soon as any CRUD operation is performed on the Drupal site.') . '<br><br>',
    ];

    $premium_version_text = $this->t('Available in the Premium version');
    $row['keycloak_sync_scheduler_provisioning_button'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this->t('&#9881; Configure'),
      '#attributes' => ['style' => 'margin-left:33%;'],
      '#disabled' => TRUE,
      '#prefix' => '<div class="mo_keycloak_sync_text_center"><h4>' . $this->t('Scheduler based Provisioning') . ' <a href="upgrade-plans"><img class="scim_client_know_more" src="' . $this->urlPath . '/crown.png" alt="Premium"><span class="scim_client_know_more_hidden">' . $premium_version_text . '</span></a></h4></div><hr>' . $this->t('In this method, you can schedule the provisioning of the users after particular interval.') . '<br>' . $this->t('It can be based on the CRON of the system. Also, you can schedule your own time to provision users.') . '<br><br>',
    ];

    return $row;
  }

  /**
   * For returning to how to perform sync page.
   */
  public function backBtnProvisioningType(array &$form, FormStateInterface $form_state) {
    $this->configFactory->set('keycloak_user_provisioning_status', 'how-to-perform-sync')->save();
    $url = Url::fromRoute('keycloak_user_provisioning.overview', [], ['query' => ['tab' => 'how-to-perform-sync']]);
    $form_state->setRedirectUrl($url);
  }

  /**
   * For redirecting user to drupal to keycloak configuration page.
   */
  public function performSyncFunction(array &$form, FormStateInterface $form_state) {
    $url = Url::fromRoute('keycloak_user_provisioning.mo_drupal_to_keycloak');
    $form_state->setRedirectUrl($url);
  }

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

}
