<?php

namespace Drupal\straker_translate\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Configure Straker Translate.
 */
class StrakerTranslateUpdateAccessTokenForm extends StrakerTranslateConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'straker_translate.account_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $accountConfig = $this->config('straker_translate.account');
    $domain = $accountConfig->get('domain');
    $straker_connect_link = $domain . '/settings?tab=keys';

    $form['account']['access_token'] = [
      '#type'        => 'textfield',
      '#title'       => t('Access Token'),
      '#description' => t('The token currently used when communicating with the Straker Translate service.'),
    ];

    $form['account_types']['existing_account']['cta'] = [
      '#type' => 'link',
      '#title' => $this->t('Generate new access token'),
      '#url' => Url::fromUri($straker_connect_link),
      '#attributes' => ['class' => ['straker_translate_signup_box_cta', 'straker_translate_signup_box_main_cta'], 'target' => '_blank'],
    ];

    $form['actions']['submit']['#value'] = t('Save Token');

    $form['actions']['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#submit' => ['::cancelForm'],
      '#attributes' => ['class' => ['button']],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $access_token = \Drupal::request()->get("access_token");
    if (empty($access_token)) {
      $this->messenger()->addError($this->t('The access token is empty. Please provide a valid access token.'));
      return;
    }
    $form_state->setRedirect('straker_translate.setup_account_handshake', ['access_token' => $access_token], []);
  }

  /**
   * {@inheritdoc}
   */
  public function cancelForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect('straker_translate.settings');
  }

}
