<?php

namespace Drupal\nodehive_admin\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller for NodeHive administration dashboard.
 */
class AdminDashboardController extends ControllerBase {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * Constructs an AdminDashboardController object.
   *
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system service.
   */
  public function __construct(Connection $database, FileSystemInterface $file_system) {
    $this->database = $database;
    $this->fileSystem = $file_system;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database'),
      $container->get('file_system'),
    );
  }

  /**
   * Displays the NodeHive administration dashboard.
   */
  public function dashboard() {
    $build = [];

    // Get statistics.
    $database = $this->database;

    // Count users.
    $user_count = $database->query('SELECT COUNT(*) FROM {users} WHERE uid > 0')->fetchField();

    // Count nodes.
    $node_count = $database->query('SELECT COUNT(*) FROM {node}')->fetchField();

    // Count spaces (if entity type exists).
    $space_count = 0;
    if ($this->entityTypeManager()->hasDefinition('nodehive_space')) {
      $space_storage = $this->entityTypeManager()->getStorage('nodehive_space');
      $query = $space_storage->getQuery();
      $query->accessCheck(FALSE);
      $space_count = $query->count()->execute();
    }

    // Get disk usage (uploaded files only).
    $public_path = $this->fileSystem->realpath("public://");
    $private_path = $this->fileSystem->realpath("private://");

    $public_size = $this->getDirectorySize($public_path);
    $private_size = $this->getDirectorySize($private_path);
    $total_size_bytes = $public_size + $private_size;

    // Convert to MB.
    $disk_usage_mb = round($total_size_bytes / (1024 * 1024), 2);

    // SVG icon definitions.
    $icons = [
      'users' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>',
      'content' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg>',
      'spaces' => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-miterlimit="10"><path d="M16.7251 10.7273C16.8951 10.6302 17 10.4495 17 10.2537L17 5.17312C17 4.97737 16.8951 4.79663 16.7251 4.69953L12.27 2.15429C12.1024 2.05849 11.8965 2.0585 11.7289 2.15431L7.27458 4.69952C7.10464 4.79663 6.99975 4.97736 6.99975 5.17309L6.99975 10.2538C6.99975 10.4495 7.10463 10.6302 7.27458 10.7273L11.7289 13.2726C11.8965 13.3684 12.1024 13.3684 12.27 13.2726L16.7251 10.7273Z"/><path d="M11.7252 19.3005C11.8951 19.2034 12 19.0226 12 18.8269L12 13.7454C12 13.5496 11.8951 13.3689 11.7252 13.2718L7.27092 10.7266C7.10324 10.6308 6.89739 10.6308 6.72971 10.7266L2.27546 13.2718C2.10552 13.3689 2.00063 13.5496 2.00063 13.7454L2.00063 18.8269C2.00063 19.0226 2.10552 19.2034 2.27546 19.3005L6.72971 21.8457C6.89739 21.9415 7.10324 21.9415 7.27092 21.8457L11.7252 19.3005Z"/><path d="M21.7252 19.3005C21.8951 19.2034 22 19.0226 22 18.8269L22 13.7454C22 13.5496 21.8951 13.3689 21.7252 13.2718L17.2709 10.7266C17.1032 10.6308 16.8974 10.6308 16.7297 10.7266L12.2746 13.2718C12.1047 13.3689 11.9998 13.5496 11.9998 13.7454L11.9998 18.8269C11.9998 19.0226 12.1047 19.2034 12.2746 19.3005L16.7297 21.8457C16.8974 21.9415 17.1032 21.9415 17.2709 21.8457L21.7252 19.3005Z"/></svg>',
      'disk' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"></ellipse><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"></path><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"></path></svg>',
      'models' => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 7.35304L21 16.647C21 16.8649 20.8819 17.0656 20.6914 17.1715L12.2914 21.8381C12.1102 21.9388 11.8898 21.9388 11.7086 21.8381L3.30861 17.1715C3.11814 17.0656 3 16.8649 3 16.647L2.99998 7.35304C2.99998 7.13514 3.11812 6.93437 3.3086 6.82855L11.7086 2.16188C11.8898 2.06121 12.1102 2.06121 12.2914 2.16188L20.6914 6.82855C20.8818 6.93437 21 7.13514 21 7.35304Z"/><path d="M3.52844 7.29357L11.7086 11.8381C11.8898 11.9388 12.1102 11.9388 12.2914 11.8381L20.5 7.27777"/><path d="M12 21L12 12"/></svg>',
      'dashboards' => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z"/><path d="M12 22C8.68629 22 6 17.5228 6 12C6 6.47715 8.68629 2 12 2"/></svg>',
      'dam' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>',
      'apps' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>',
      'settings' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>',
      'subscription' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line></svg>',
      'api' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>',
      'keys' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path></svg>',
      'env' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2" ry="2"></rect><rect x="9" y="9" width="6" height="6"></rect><line x1="9" y1="1" x2="9" y2="4"></line><line x1="15" y1="1" x2="15" y2="4"></line><line x1="9" y1="20" x2="9" y2="23"></line><line x1="15" y1="20" x2="15" y2="23"></line><line x1="20" y1="9" x2="23" y2="9"></line><line x1="20" y1="14" x2="23" y2="14"></line><line x1="1" y1="9" x2="4" y2="9"></line><line x1="1" y1="14" x2="4" y2="14"></line></svg>',
      'permissions' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>',
      'logs' => '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="17" y1="10" x2="3" y2="10"></line><line x1="21" y1="6" x2="3" y2="6"></line><line x1="21" y1="14" x2="3" y2="14"></line><line x1="17" y1="18" x2="3" y2="18"></line></svg>',
    ];

    // Build clickable stats section.
    $build['stats'] = [
      '#type' => 'container',
      '#attributes' => ['class' => ['nodehive-stats']],
    ];

    $stats = [
      [
        'label' => $this->t('Users'),
        'value' => $user_count,
        'icon' => $icons['users'],
        'path' => '/nodehive/users',
      ],
      [
        'label' => $this->t('Content'),
        'value' => $node_count,
        'icon' => $icons['content'],
        'path' => '/nodehive/admin/content',
      ],
      [
        'label' => $this->t('Spaces'),
        'value' => $space_count,
        'icon' => $icons['spaces'],
        'path' => '/admin/content/space',
      ],
      [
        'label' => $this->t('Disk Usage'),
        'value' => $disk_usage_mb,
        'subvalue' => 'MB',
        'icon' => $icons['disk'],
        'path' => '/admin/reports/status',
      ],
    ];

    foreach ($stats as $key => $stat) {
      $subvalue = isset($stat['subvalue']) ? '<span class="stat-subvalue">' . $stat['subvalue'] . '</span>' : '';
      $build['stats'][$key] = [
        '#markup' => Markup::create('<a href="' . Url::fromUserInput($stat['path'])->toString() . '" class="stat-item">' .
          '<span class="stat-icon">' . $stat['icon'] . '</span>' .
          '<span class="stat-content">' .
          '<span class="stat-value">' . $stat['value'] . '</span>' .
          $subvalue .
          '<span class="stat-label">' . $stat['label'] . '</span>' .
          '</span>' .
          '</a>'),
      ];
    }

    // Define sections grouped by persona.
    $section_groups = [
      'content' => [
        'title' => $this->t('Content & Spaces'),
        'sections' => [
          [
            'title' => $this->t('Spaces'),
            'description' => $this->t('Manage spaces and multi-tenancy'),
            'icon' => $icons['spaces'],
            'path' => '/admin/content/space',
            'permission' => 'access content overview',
          ],
          [
            'title' => $this->t('Content Models'),
            'description' => $this->t('Manage content types and data models'),
            'icon' => $icons['models'],
            'path' => '/nodehive/models',
            'permission' => 'access content overview',
          ],
          [
            'title' => $this->t('Dashboards'),
            'description' => $this->t('Configure and manage dashboards'),
            'icon' => $icons['dashboards'],
            'path' => '/admin/dashboards/list',
            'permission' => 'access content overview',
          ],
          [
            'title' => $this->t('Digital Assets'),
            'description' => $this->t('Manage media files and images'),
            'icon' => $icons['dam'],
            'path' => '/nodehive/admin/dam',
            'permission' => 'access content overview',
          ],
          [
            'title' => $this->t('Apps'),
            'description' => $this->t('Installed apps and integrations'),
            'icon' => $icons['apps'],
            'path' => '/nodehive/apps',
            'permission' => 'access content overview',
          ],
        ],
      ],
      'admin' => [
        'title' => $this->t('Administration'),
        'sections' => [
          [
            'title' => $this->t('Users'),
            'description' => $this->t('Manage user accounts and permissions'),
            'icon' => $icons['users'],
            'path' => '/nodehive/users',
            'permission' => 'administer users',
          ],
          [
            'title' => $this->t('Settings'),
            'description' => $this->t('Configure NodeHive system settings'),
            'icon' => $icons['settings'],
            'path' => '/nodehive/settings',
            'permission' => 'administer site configuration',
          ],
          [
            'title' => $this->t('Subscription'),
            'description' => $this->t('Manage your NodeHive subscription and billing'),
            'icon' => $icons['subscription'],
            'path' => '/nodehive/subscription',
            'permission' => 'access content overview',
          ],
        ],
      ],
      'developer' => [
        'title' => $this->t('Developer Tools'),
        'sections' => [
          [
            'title' => $this->t('API Documentation'),
            'description' => $this->t('Browse and test API endpoints'),
            'icon' => $icons['api'],
            'path' => '/nodehive/api-explorer',
            'permission' => 'view nodehive api documentation',
          ],
          [
            'title' => $this->t('API Keys'),
            'description' => $this->t('Manage API keys for external access'),
            'icon' => $icons['keys'],
            'path' => '/nodehive/api-keys',
            'permission' => 'administer site configuration',
          ],
          [
            'title' => $this->t('Environment Variables'),
            'description' => $this->t('Configure frontend environment variables'),
            'icon' => $icons['env'],
            'path' => '/nodehive/env-vars',
            'permission' => 'administer site configuration',
          ],
          [
            'title' => $this->t('Permissions'),
            'description' => $this->t('Configure user roles and permissions'),
            'icon' => $icons['permissions'],
            'path' => '/admin/people/permissions',
            'permission' => 'administer permissions',
          ],
          [
            'title' => $this->t('Logs'),
            'description' => $this->t('View system logs and error reports'),
            'icon' => $icons['logs'],
            'path' => '/admin/reports/dblog',
            'permission' => 'access site reports',
          ],
        ],
      ],
    ];

    $current_user = $this->currentUser();

    // Build grouped sections.
    foreach ($section_groups as $group_key => $group) {
      $build[$group_key . '_heading'] = [
        '#markup' => '<h2 class="nodehive-section-heading">' . $group['title'] . '</h2>',
      ];

      $build[$group_key . '_sections'] = [
        '#type' => 'container',
        '#attributes' => ['class' => ['nodehive-admin-grid']],
      ];

      foreach ($group['sections'] as $key => $section) {
        // Check permission if specified.
        if (isset($section['permission']) && !$current_user->hasPermission($section['permission'])) {
          continue;
        }

        $card_key = $group_key . '_' . $key;

        $build[$group_key . '_sections'][$card_key] = [
          '#type' => 'link',
          '#title' => Markup::create('<span class="card-icon">' . $section['icon'] . '</span>' .
            '<span class="card-content">' .
            '<span class="card-title">' . $section['title'] . '</span>' .
            '<span class="card-description">' . $section['description'] . '</span>' .
            '</span>'),
          '#url' => Url::fromUserInput($section['path']),
          '#attributes' => ['class' => ['nodehive-admin-card']],
        ];
      }
    }

    $build['#attached']['library'][] = 'nodehive_admin/admin_dashboard';

    return $build;
  }

  /**
   * Calculates the total size of a directory.
   *
   * @param string $directory
   *   The directory path.
   *
   * @return int
   *   The total size of the directory in bytes.
   */
  protected function getDirectorySize($directory) {
    $size = 0;
    if (!$directory || !is_dir($directory)) {
      return $size;
    }
    try {
      foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)) as $file) {
        if ($file->isFile()) {
          $size += $file->getSize();
        }
      }
    }
    catch (\Exception $e) {
      $this->logger('nodehive_admin')->error('Error calculating directory size: @message', ['@message' => $e->getMessage()]);
    }
    return $size;
  }

}
