<?php

namespace Drupal\nodehive_api_key_management\Form;

use Drupal\Core\Url;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\nodehive_api_key_management\Service\ApiKeyManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form for editing an existing API key.
 */
class ApiKeyEditForm extends FormBase {

  /**
   * The API key manager service.
   *
   * @var \Drupal\nodehive_api_key_management\Service\ApiKeyManager
   */
  protected $apiKeyManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * Constructs an ApiKeyEditForm object.
   */
  public function __construct(ApiKeyManager $api_key_manager, EntityTypeManagerInterface $entity_type_manager, DateFormatterInterface $date_formatter) {
    $this->apiKeyManager = $api_key_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->dateFormatter = $date_formatter;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $key_id = NULL) {
    $key = $this->apiKeyManager->loadKey($key_id);

    if (!$key) {
      $this->messenger()->addError($this->t('API key not found.'));
      return $form;
    }

    $form['key_id'] = [
      '#type' => 'value',
      '#value' => $key_id,
    ];

    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Key Name'),
      '#default_value' => $key->name,
      '#required' => TRUE,
    ];

    $form['uid'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#title' => $this->t('User'),
      '#description' => $this->t('The user account this API key will authenticate as.'),
      '#default_value' => $this->entityTypeManager->getStorage('user')->load($key->uid),
      '#required' => TRUE,
    ];

    $form['status'] = [
      '#type' => 'radios',
      '#title' => $this->t('Status'),
      '#options' => [
        1 => $this->t('Active'),
        0 => $this->t('Revoked'),
      ],
      '#default_value' => $key->status,
      '#required' => TRUE,
    ];

    $form['rate_limit'] = [
      '#type' => 'number',
      '#title' => $this->t('Rate Limit'),
      '#default_value' => $key->rate_limit,
      '#min' => 0,
      '#required' => TRUE,
    ];

    $form['expiry'] = [
      '#type' => 'datetime',
      '#title' => $this->t('Expiry Date'),
      '#default_value' => $key->expiry ? DrupalDateTime::createFromTimestamp($key->expiry) : NULL,
    ];

    $form['ip_allowlist'] = [
      '#type' => 'textarea',
      '#title' => $this->t('IP Allowlist (JSON)'),
      '#default_value' => $key->ip_allowlist,
      '#rows' => 3,
    ];

    $form['info'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Key Information'),
    ];

    $form['info']['prefix'] = [
      '#markup' => '<p><strong>' . $this->t('Key Prefix:') . '</strong> ' . $key->key_prefix . '</p>',
    ];

    $form['info']['created'] = [
      '#markup' => '<p><strong>' . $this->t('Created:') . '</strong> ' . $this->dateFormatter->format($key->created) . '</p>',
    ];

    $form['info']['last_used'] = [
      '#markup' => '<p><strong>' . $this->t('Last Used:') . '</strong> ' . ($key->last_used ? $this->dateFormatter->format($key->last_used) : $this->t('Never')) . '</p>',
    ];

    $form['info']['use_count'] = [
      '#markup' => '<p><strong>' . $this->t('Use Count:') . '</strong> ' . $key->use_count . '</p>',
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    ];

    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromRoute('nodehive_api_key_management.list'),
      '#attributes' => ['class' => ['button']],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Validate IP allowlist JSON if provided.
    $ip_allowlist = trim($form_state->getValue('ip_allowlist'));
    if (!empty($ip_allowlist)) {
      json_decode($ip_allowlist, TRUE);
      if (json_last_error() !== JSON_ERROR_NONE) {
        $form_state->setErrorByName('ip_allowlist', $this->t('Invalid JSON format for IP allowlist.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $key_id = $form_state->getValue('key_id');

    $fields = [
      'name' => $form_state->getValue('name'),
      'uid' => $form_state->getValue('uid'),
      'status' => $form_state->getValue('status'),
      'rate_limit' => $form_state->getValue('rate_limit'),
    ];

    // Handle expiry.
    $expiry = $form_state->getValue('expiry');
    if ($expiry) {
      $fields['expiry'] = $expiry->getTimestamp();
    }
    else {
      $fields['expiry'] = NULL;
    }

    // Handle IP allowlist.
    $ip_allowlist = trim($form_state->getValue('ip_allowlist'));
    if (!empty($ip_allowlist)) {
      $fields['ip_allowlist'] = json_decode($ip_allowlist, TRUE);
    }
    else {
      $fields['ip_allowlist'] = NULL;
    }

    if ($this->apiKeyManager->updateKey($key_id, $fields)) {
      $this->messenger()->addStatus($this->t('API key updated successfully.'));
    }
    else {
      $this->messenger()->addError($this->t('Failed to update API key.'));
    }

    $form_state->setRedirect('nodehive_api_key_management.list');
  }

}
