<?php

namespace Drupal\nodehive_core\Form;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a base form for user.
 */
abstract class UserAddEditBaseForm extends FormBase {

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

  /**
   * The route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * The module_handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The form builder service.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * Constructs a new SpaceUserBaseForm.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module_handler service.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder service.
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    RouteMatchInterface $route_match,
    ModuleHandlerInterface $module_handler,
    FormBuilderInterface $form_builder,
  ) {
    $this->entityTypeManager = $entity_type_manager;
    $this->routeMatch = $route_match;
    $this->moduleHandler = $module_handler;
    $this->formBuilder = $form_builder;
  }

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

  /**
   * Gets the entity type manager.
   *
   * @return \Drupal\Core\Entity\EntityTypeManagerInterface
   *   Entity type manager.
   */
  protected function entityTypeManager() {
    return $this->entityTypeManager;
  }

  /**
   * Gets the module handler.
   *
   * @return \Drupal\Core\Extension\ModuleHandlerInterface
   *   Module handeler.
   */
  protected function moduleHandler() {
    return $this->moduleHandler;
  }

  /**
   * Gets the form builder.
   *
   * @return \Drupal\Core\Form\FormBuilderInterface
   *   Form builder.
   */
  protected function formBuilder() {
    return $this->formBuilder;
  }

  /**
   * Gets the basic user form.
   *
   * @return array
   *   Render array.
   */
  protected function getBaseUserForm(UserInterface $user): array {
    $form = [];

    $form['mail'] = [
      '#type' => 'email',
      '#title' => $this->t('Email address'),
      '#states' => [
        'required' => [
          ':input[name="type"]' => ['value' => 'new'],
        ],
      ],
      '#default_value' => $user->isNew() ? NULL : $user->getEmail(),
    ];

    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#states' => [
        'required' => [
          ':input[name="type"]' => ['value' => 'new'],
        ],
      ],
      '#default_value' => $user->isNew() ? NULL : $user->getAccountName(),
    ];

    $form['password'] = [
      '#type' => 'password',
      '#title' => $this->t('Password'),
      '#states' => [
        'required' => [
          ':input[name="type"]' => ['value' => 'new'],
        ],
      ],
    ];

    $form['confirm_password'] = [
      '#type' => 'password',
      '#title' => $this->t('Confirm Password'),
      '#states' => [
        'required' => [
          ':input[name="type"]' => ['value' => 'new'],
        ],
      ],
    ];

    $form['status'] = [
      '#type' => 'radios',
      '#title' => $this->t('Status'),
      '#options' => [
        0 => $this->t('Blocked'),
        1 => $this->t('Active'),
      ],
      '#default_value' => $user->isNew() ? TRUE : $user->status->value,
    ];

    $roles = [];
    if (!$user->isNew()) {
      foreach ($user->getRoles() as $rid) {
        // If (str_contains($rid, "nodehive_")) {.
        $roles[] = $rid;
        // }
      }
    }

    // Load all roles except 'administrator'.
    $roles_entities = $this->entityTypeManager()
      ->getStorage('user_role')
      ->loadMultiple();

    $roles_options = [];
    foreach ($roles_entities as $role_id => $role_entity) {
      // Skip 'administrator' role.
      if ($role_id !== 'administrator' && $role_id !== 'anonymous' && $role_id !== 'authenticated') {
        $roles_options[$role_id] = $role_entity->label();
      }
    }

    $form['roles'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Roles'),
    // Use filtered or full roles options.
      '#options' => $roles_options,
    // Assuming $roles is calculated somewhere as per your previous code.
      '#default_value' => $roles,
    ];

    $spaces = $this->entityTypeManager()
      ->getStorage('nodehive_space')
      ->loadMultiple();

    $spaces_options = [];
    $current_user_spaces = [];
    foreach ($spaces as $space) {
      $spaces_options[$space->id()] = $space->label();

      /** @var \Drupal\user\UserInterface $editor */
      foreach ($space->editors->referencedEntities() as $editor) {
        if ($editor->id() == $user->id()) {
          $current_user_spaces[] = $space->id();
        }
      }
    }

    $form['spaces'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Spaces'),
      '#options' => $spaces_options,
      '#default_value' => $user->isNew() ? [] : $current_user_spaces,
    ];

    $form['picture_wrapper'] = [
      '#type' => 'details',
      '#title' => $this->t('Picture'),
      '#open' => TRUE,
    ];

    $form['picture_wrapper']['picture'] = [
      '#type' => 'managed_file',
      '#upload_location' => 'public://',
      '#multiple' => FALSE,
      '#description' => $this->t('Allowed extensions: gif png jpg jpeg'),
      '#upload_validators' => [
        'file_validate_is_image' => [],
        'file_validate_extensions' => ['gif png jpg jpeg'],
        'file_validate_size' => [25600000],
      ],
      '#title' => $this->t('Upload an image file for this user'),
      '#default_value' => (!$user->isNew() && $user->user_picture->target_id) ? [$user->user_picture->target_id] : NULL,
    ];

    if ($user->isNew()) {
      $form['notify'] = [
        '#type' => 'checkbox',
        '#title' => $this->t('Notify user of a new account.'),
        '#default_value' => FALSE,
      ];
    }

    $form['advanced'] = [
      '#type' => 'details',
      '#title' => $this->t("Advanced Settings"),
      '#open' => FALSE,
    ];

    $user_form = $this->entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity($user);
    $user_form = $this->formBuilder()->getForm($user_form);

    $form['advanced']['language'] = [
      '#type' => 'language_select',
      '#title' => $this->t('Site Language'),
      '#languages' => LanguageInterface::STATE_ALL,
      '#default_value' => $user->getPreferredLangcode(),
    ];

    $form['advanced']['timezone'] = [
      '#type' => 'select',
      '#title' => $this->t('Time zone'),
      '#options' => $user_form['timezone']['timezone']['#options'],
      '#default_value' => $user->isNew() ? "UTC" : $user->getTimeZone(),
    ];

    return $form;
  }

}
