<?php

declare(strict_types=1);

namespace App\Application\Admin\Service;

use App\Framework\Router\UrlGenerator;

final readonly class AdminNavigationService
{
    public function __construct(
        private UrlGenerator $urlGenerator
    ) {
    }

    public function getNavigationMenu(): array
    {
        error_log("AdminNavigationService: Starting navigation menu generation");

        $menuDefinition = [
            'System' => [
                'icon' => 'server',
                'routes' => [
                    'Dashboard' => 'admin.dashboard',
                    'Performance' => 'admin.system.performance',
                    'Environment' => 'admin.system.environment',
                    'Health Check' => 'admin.system.health',
                    'PHP Info' => 'admin.system.phpinfo',
                ],
            ],
            'Infrastructure' => [
                'icon' => 'database',
                'routes' => [
                    'Redis' => 'admin.infrastructure.redis',
                    'Cache Metrics' => 'admin.infrastructure.cache',
                    'Services' => 'admin.infrastructure.services',
                ],
                'static' => [
                    'Logs' => '/admin/infrastructure/logs', // TODO: Add named route
                ],
            ],
            'Development' => [
                'icon' => 'code',
                'routes' => [
                    'Routes' => 'admin.dev.routes',
                    'Design System' => 'admin.dev.design-system',
                    'WAF Testing' => 'admin.dev.waf-test',
                ],
                'static' => [
                    'Style Guide' => '/admin/dev/styleguide', // TODO: Add named route
                ],
            ],
            'Analytics' => [
                'icon' => 'chart-bar',
                'routes' => [
                    'Dashboard' => 'admin.analytics.dashboard',
                ],
            ],
            'Content' => [
                'icon' => 'photo',
                'routes' => [
                    'Image Manager' => 'admin.content.images',
                    'Image Slots' => 'admin.content.image-slots',
                ],
            ],
        ];

        $menu = [];

        foreach ($menuDefinition as $sectionName => $sectionData) {
            error_log("AdminNavigationService: Processing section '{$sectionName}'");

            $items = [];

            // Process routes
            if (isset($sectionData['routes'])) {
                foreach ($sectionData['routes'] as $itemName => $routeName) {
                    try {
                        $items[$itemName] = $this->urlGenerator->route($routeName);
                        error_log("AdminNavigationService: Successfully generated route '{$routeName}' for '{$itemName}'");
                    } catch (\Exception $e) {
                        error_log("AdminNavigationService: Failed to generate route '{$routeName}' for '{$itemName}': " . $e->getMessage());

                        // Generate fallback URL from route name - better mapping
                        $fallbackUrl = match ($routeName) {
                            'admin.dashboard' => '/admin',
                            'admin.system.health' => '/admin/system/health',
                            'admin.system.phpinfo' => '/admin/system/phpinfo',
                            'admin.system.performance' => '/admin/system/performance',
                            'admin.system.environment' => '/admin/system/environment',
                            'admin.infrastructure.redis' => '/admin/infrastructure/redis',
                            'admin.infrastructure.cache' => '/admin/infrastructure/cache',
                            'admin.infrastructure.services' => '/admin/infrastructure/services',
                            'admin.dev.routes' => '/admin/dev/routes',
                            'admin.dev.design-system' => '/admin/dev/design-system',
                            'admin.dev.waf-test' => '/admin/dev/waf-test',
                            'admin.analytics.dashboard' => '/admin/analytics/dashboard',
                            'admin.content.images' => '/admin/content/images',
                            'admin.content.image-slots' => '/admin/content/image-slots',
                            default => '/' . str_replace('.', '/', $routeName)
                        };

                        $items[$itemName] = $fallbackUrl;
                        error_log("AdminNavigationService: Using fallback URL '{$fallbackUrl}' for '{$itemName}'");
                    }
                }
            }

            // Add static routes
            if (isset($sectionData['static'])) {
                foreach ($sectionData['static'] as $itemName => $url) {
                    $items[$itemName] = $url;
                    error_log("AdminNavigationService: Added static route '{$url}' for '{$itemName}'");
                }
            }

            $menu[$sectionName] = [
                'icon' => $sectionData['icon'],
                'items' => $items,
            ];
        }

        error_log("AdminNavigationService: Successfully completed navigation menu generation");

        return $menu;
    }

    public function getCurrentSection(string $currentPath): ?string
    {
        $menu = $this->getNavigationMenu();

        foreach ($menu as $section => $data) {
            foreach ($data['items'] as $name => $url) {
                if (str_starts_with($currentPath, $url)) {
                    return $section;
                }
            }
        }

        return null;
    }

    public function getBreadcrumbs(string $currentPath): array
    {
        $menu = $this->getNavigationMenu();
        $breadcrumbs = [
            ['name' => 'Admin', 'url' => $this->urlGenerator->route('admin.dashboard')],
        ];

        foreach ($menu as $section => $data) {
            foreach ($data['items'] as $name => $url) {
                if ($currentPath === $url || str_starts_with($currentPath, $url)) {
                    if ($url !== $this->urlGenerator->route('admin.dashboard')) {
                        $breadcrumbs[] = ['name' => $section, 'url' => null];
                        $breadcrumbs[] = ['name' => $name, 'url' => $url];
                    }

                    return $breadcrumbs;
                }
            }
        }

        return $breadcrumbs;
    }

    public function getActiveMenuItem(string $currentPath): ?string
    {
        $menu = $this->getNavigationMenu();

        foreach ($menu as $section => $data) {
            foreach ($data['items'] as $name => $url) {
                if ($currentPath === $url || str_starts_with($currentPath, $url)) {
                    return $name;
                }
            }
        }

        return null;
    }
}
