<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Datetime\TimeInterface;

/**
 * Provides a 'MyRecentNodeEditsBlock' block.
 *
 * @DashboardBlock(
 *   id = "my_recent_node_edits_block",
 *   name = @Translation("My Recent Edits"),
 *   category = "Content",
 *   id_category = "content"
 * )
 */
class MyRecentNodeEditsBlock extends DashboardBlockBase implements ContainerFactoryPluginInterface {
  use StringTranslationTrait;

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

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->dateFormatter = $container->get('date.formatter');
    $instance->time = $container->get('datetime.time');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $block_configuration = $this->getConfiguration();
    // Get the configured number of items, default to 10.
    $num_items = $block_configuration['plugin_specific_config']['num_items'] ?? 10;

    // Get the configured workflow, default to 'editorial'.
    $selected_workflow = $block_configuration['plugin_specific_config']['workflow'] ?? 'editorial';

    // Get the current user's ID.
    $current_user_id = $this->currentUser->id();

    // Modify the node query to filter by the current user.
    $node_query = $this->entityTypeManager->getStorage('node')
      ->getQuery()
    // Add this line to filter by current user.
      ->condition('uid', $current_user_id)
      ->accessCheck(TRUE)
      ->sort('changed', 'DESC')
      ->range(0, $num_items);

    $node_ids = $node_query->execute();

    // Load the node entities.
    $nodes = $this->entityTypeManager->getStorage('node')
      ->loadMultiple($node_ids);

    $header = [
      'title' => $this->t('Title'),
      'language' => $this->t('Language'),
      'workflow_state' => $this->t('Workflow State'),
      'author' => $this->t('Author'),
      'last_edited' => $this->t('Last Edited'),
      'space' => $this->t('Space'),
      'view_link' => '',
      'edit_link' => '',
    ];

    $build['nodes_table'] = [
      '#type' => 'table',
      '#header' => $header,
    ];

    foreach ($nodes as $node) {
      // Create the link to the node detail page.
      $node_url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()]);
      $node_link = Link::fromTextAndUrl($node->label(), $node_url)->toString();
      $view_link = Link::fromTextAndUrl($this->t('View'), $node_url)->toString();

      // Create the edit link.
      $edit_url = Url::fromRoute('entity.node.edit_form', ['node' => $node->id()]);
      $edit_link = Link::fromTextAndUrl($this->t('Edit'), $edit_url)->toString();

      // Retrieve the workflow state label.
      $workflow_state = '';
      if ($node->hasField('moderation_state') && !$node->get('moderation_state')->isEmpty()) {
        $state_id = $node->get('moderation_state')->value;
        $workflow = $this->entityTypeManager
          ->getStorage('workflow')
          ->load($selected_workflow);

        if ($workflow) {
          $state = $workflow->getTypePlugin()->getState($state_id);
          if ($state) {
            $workflow_state = $state->label();
          }
        }
      }

      // Retrieve the author's name.
      $author_name = '';
      if ($node->hasField('uid') && !$node->get('uid')->isEmpty()) {
        $author_id = $node->get('uid')->target_id;
        $author_user = $this->entityTypeManager
          ->getStorage('user')
          ->load($author_id);

        if ($author_user) {
          $author_name = $author_user->getDisplayName();
        }
      }

      // Format the last edited date.
      $last_edited = $this->dateFormatter->formatDiff($node->getChangedTime(), $this->time->getRequestTime());

      // Retrieve and format the space information.
      $space_label = '';
      if ($node->hasField('nodehive_space') && !$node->get('nodehive_space')->isEmpty()) {
        $space_id = $node->get('nodehive_space')->target_id;
        $space_entity = $this->entityTypeManager
          ->getStorage('nodehive_space')
          ->load($space_id);

        if ($space_entity) {
          // Create the link to the space detail page.
          $space_url = Url::fromRoute('entity.nodehive_space.canonical', ['nodehive_space' => $space_id]);
          $space_link = Link::fromTextAndUrl($space_entity->label(), $space_url)->toString();
          $space_label = $space_link;
        }
      }
      else {
        $space_label = 'not set';
      }

      $build['nodes_table'][] = [
        'title' => ['#markup' => $node_link],
        'language' => ['#markup' => $node->language()->getName()],
        'workflow_state' => ['#markup' => $workflow_state],
        'author' => ['#markup' => $author_name],
        'last_edited' => ['#markup' => $last_edited],
        'space' => ['#markup' => $space_label],
        'view_link' => ['#markup' => $view_link],
        'edit_link' => ['#markup' => $edit_link],
      ];
    }

    // Create the URL with a query parameter for the author.
    $kanban_url = Url::fromRoute('content_kanban.kanban', [], [
      'query' => [
        'author' => $current_user_id,
      ],
    ]);

    $build['link'] = [
      '#type' => 'link',
      '#title' => $this->t('Show more'),
      '#url' => $kanban_url,
      '#attributes' => [
        'class' => ['button', 'button--small'],
      ],
      '#weight' => '50',
    ];

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfigSpecificFormFields(
    FormStateInterface &$form_state,
    Request &$request,
    array $block_configuration,
  ) {
    $form = [];

    // Field to configure the number of items to display.
    $form['num_items'] = [
      '#type' => 'number',
      '#title' => $this->t('Number of Items'),
      '#description' => $this->t('The number of recent edits to display.'),
      '#default_value' => $block_configuration['plugin_specific_config']['num_items'] ?? 10,
      '#min' => 1,
      '#required' => TRUE,
    ];

    // Retrieve all available workflows for the select options.
    $workflows = $this->entityTypeManager
      ->getStorage('workflow')
      ->loadMultiple();

    $workflow_options = array_map(function ($workflow) {
      return $workflow->label();
    }, $workflows);

    // Field to select the workflow.
    $form['workflow'] = [
      '#type' => 'select',
      '#title' => $this->t('Workflow'),
      '#description' => $this->t('Select the workflow.'),
      '#options' => $workflow_options,
      '#default_value' => $block_configuration['plugin_specific_config']['workflow'] ?? 'editorial',
      '#required' => TRUE,
    ];

    return $form;
  }

}
