<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use GuzzleHttp\Exception\RequestException;

/**
 * Provides a MatomoGoalWidget block for Content Planner Dashboard.
 *
 * @DashboardBlock(
 *   id = "matomo_goal_widget",
 *   name = @Translation("Matomo Goal Widget"),
 *   category = "Site Analytics",
 *   id_category = "site_analytics"
 * )
 */
class MatomoGoalWidget extends DashboardBlockBase {
  use StringTranslationTrait;

  /**
   * The HTTP client to fetch the stats.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->httpClient = $container->get('http_client');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();

    // Check if required configuration exists.
    if (
          !isset(
              $config['plugin_specific_config']['matomo_url'],
              $config['plugin_specific_config']['site_id'],
              $config['plugin_specific_config']['api_key'],
              $config['plugin_specific_config']['metric'],
              $config['plugin_specific_config']['start_date'],
              $config['plugin_specific_config']['end_date'],
              $config['plugin_specific_config']['goal']
          )
      ) {
      return [
        '#markup' => $this->t('Please configure the Matomo settings and goal details in the dashboard block configuration.'),
      ];
    }

    // Retrieve configuration values.
    $matomo_url = $config['plugin_specific_config']['matomo_url'];
    $site_id = $config['plugin_specific_config']['site_id'];
    $api_key = $config['plugin_specific_config']['api_key'];
    $metric = $config['plugin_specific_config']['metric'];
    $start_date = $config['plugin_specific_config']['start_date'];
    $end_date = $config['plugin_specific_config']['end_date'];
    $goal_value = $config['plugin_specific_config']['goal'];

    // Map metrics to their respective methods.
    $metric_methods = [
      'nb_visits' => 'VisitsSummary.get',
      'nb_pageviews' => 'Actions.get',
      'nb_uniq_pageviews' => 'Actions.get',
    ];

    $method = $metric_methods[$metric] ?? 'Actions.get';

    try {
      // Make API request.
      $response = $this->httpClient->request('GET', $matomo_url . '/index.php', [
        'query' => [
          'module' => 'API',
          'method' => $method,
          'idSite' => $site_id,
          'period' => 'range',
          'date' => $start_date . ',' . $end_date,
          'format' => 'json',
          'token_auth' => $api_key,
        ],
      ]);

      $data = json_decode($response->getBody(), TRUE);
      $current_value = $data[$metric] ?? 0;
      $progress_percentage = min(($current_value / $goal_value) * 100, 100);

      // Date calculations.
      $current_date = new \DateTime();
      $start_date_obj = new \DateTime($start_date);
      $end_date_obj = new \DateTime($end_date);

      // Calculate the time progress for today.
      $total_duration = $start_date_obj->diff($end_date_obj)->days;
      $elapsed_duration = $start_date_obj->diff($current_date)->days;
      $time_progress_percentage = min(($elapsed_duration / $total_duration) * 100, 100);

      // Determine progress text.
      if ($current_date > $end_date_obj) {
        $progress_text = $progress_percentage >= 100
                  ? $this->t('Goal achieved!')
                  : $this->t('Goal not achieved');
      }
      else {
        $progress_text = $progress_percentage >= $time_progress_percentage
                  ? $this->t('Ahead')
                  : $this->t('Behind');
      }

    }
    catch (RequestException $e) {
      return [
        '#markup' => $this->t('Failed to fetch data from Matomo: @message', ['@message' => $e->getMessage()]),
      ];
    }

    // Build output with Tailwind CSS classes, including the today marker.
    $output = '
          <div class="py-2">
              <div class="text-center text-2xl font-semibold my-2">' . number_format($current_value) . ' / ' . number_format($goal_value) . '</div>
              <div class="text-center text-sm font-semibold my-2 text-gray-400">' . $metric . '</div>
              <div class="relative bg-slate-300 rounded-full h-4 overflow-hidden">
                  <div class="bg-blue-500 h-full text-xs text-white flex items-center justify-center" style="width: ' . $progress_percentage . '%;">
                      ' . number_format($progress_percentage, 1) . '%
                  </div>
                  <!-- Today marker -->
                  <div class="absolute top-0 h-full border-l-2 border-red-500" style="left: ' . $time_progress_percentage . '%;">
                      <span class="absolute left-1/2 transform -translate-x-1/2 text-xs text-red-500 z-50">|</span>
                  </div>
              </div>
              <div class="mt-4" style="color: ' . ($progress_percentage >= 100 ? '#28a745' : '#007bff') . ';">
                  ' . $progress_text . '
              </div>
              <div class="text-gray-600 text-xs mt-4">
                  <p><strong>Date Range:</strong> ' . $start_date . ' - ' . $end_date . '</p>
              </div>
          </div>
      ';

    return [
      '#type' => 'processed_text',
      '#text' => $output,
      '#format' => 'full_html',
    ];
  }

  /**
   * Returns the human-readable label for a given metric.
   *
   * @param string $metric
   *   The metric key.
   *
   * @return string
   *   The metric label.
   */
  protected function getMetricLabel($metric) {
    $options = [
      'nb_visits' => $this->t('Sessions'),
      'nb_pageviews' => $this->t('Page Views'),
      'nb_uniq_pageviews' => $this->t('Unique Page Views'),
    ];
    return $options[$metric] ?? $metric;
  }

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

    $form['matomo_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Matomo URL'),
      '#description' => $this->t('The URL of your Matomo instance.'),
      '#default_value' => $block_configuration['plugin_specific_config']['matomo_url'] ?? '',
      '#required' => TRUE,
    ];

    $form['site_id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Site ID'),
      '#description' => $this->t('The ID of the site in Matomo you want to fetch data for.'),
      '#default_value' => $block_configuration['plugin_specific_config']['site_id'] ?? '',
      '#required' => TRUE,
    ];

    $form['api_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API Key'),
      '#description' => $this->t('The API key for authentication with Matomo.'),
      '#default_value' => $block_configuration['plugin_specific_config']['api_key'] ?? '',
      '#required' => TRUE,
    ];

    $form['metric'] = [
      '#type' => 'select',
      '#title' => $this->t('Metric'),
      '#description' => $this->t('The metric you want to track.'),
      '#options' => [
        'nb_visits' => $this->t('Sessions'),
        'nb_pageviews' => $this->t('Page Views'),
        'nb_uniq_pageviews' => $this->t('Unique Page Views'),
      ],
      '#default_value' => $block_configuration['plugin_specific_config']['metric'] ?? 'nb_pageviews',
      '#required' => TRUE,
    ];

    $form['start_date'] = [
      '#type' => 'date',
      '#title' => $this->t('Start Date'),
      '#description' => $this->t('The start date for the time range.'),
      '#default_value' => $block_configuration['plugin_specific_config']['start_date'] ?? '',
      '#required' => TRUE,
    ];

    $form['end_date'] = [
      '#type' => 'date',
      '#title' => $this->t('End Date'),
      '#description' => $this->t('The end date for the time range.'),
      '#default_value' => $block_configuration['plugin_specific_config']['end_date'] ?? '',
      '#required' => TRUE,
    ];

    $form['goal'] = [
      '#type' => 'number',
      '#title' => $this->t('Goal'),
      '#description' => $this->t('The target number for the selected metric.'),
      '#default_value' => $block_configuration['plugin_specific_config']['goal'] ?? '',
      '#required' => TRUE,
    ];

    return $form;
  }

}
