<?php

namespace Drupal\nodehive_core\Form;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a form for cancelling a user.
 */
class UserCancelAccountConfirmForm extends ConfirmFormBase {

  /**
   * User entity.
   *
   * @var \Drupal\user\UserInterface|null
   */
  protected ?UserInterface $user;

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

  /**
   * UserDeleteConfirmForm constructor.
   *
   * @param \Drupal\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->user = NULL;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $user = NULL) {
    $form = [];

    $this->user = $this->entityTypeManager->getStorage('user')->load($user);

    $form['user_cancel_method'] = [
      '#type' => 'radios',
      '#title' => $this->t('Cancellation method'),
    ];

    $form['user_cancel_method'] += user_cancel_methods();

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->user->id() == $this->currentUser()->id()) {
      $this->messenger()->addStatus($this->t(
        "You can't cancel your own account.",
      ));
    }

    user_cancel($form_state->getValues(), $this->user->id(), $form_state->getValue('user_cancel_method'));

    $this->messenger()->addStatus($this->t(
      "User @user has been cancelled successfully.",
      [
        '@user' => $this->user->getAccountName(),
      ]
    ));

    $form_state->setRedirectUrl($this->getCancelUrl());
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to cancel the user %user?', ['%user' => $this->user->getAccountName()]);
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this->t('Confirm');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('nodehive_core.users_list_builder');
  }

}
