<?php

declare(strict_types=1);

namespace App\Application\Admin\System;

use App\Application\Admin\Service\AdminLayoutProcessor;
use App\Framework\Attributes\Route;
use App\Framework\Auth\Auth;
use App\Framework\DateTime\Clock;
use App\Framework\Health\HealthCheckCategory;
use App\Framework\Health\HealthCheckManager;
use App\Framework\Http\Method;
use App\Framework\Meta\MetaData;
use App\Framework\Router\Result\JsonResult;
use App\Framework\Router\Result\ViewResult;
use App\Framework\View\Table\Generators\HealthCheckTableGenerator;

final readonly class HealthController
{
    public function __construct(
        private HealthCheckManager $healthManager,
        private AdminLayoutProcessor $layoutProcessor,
        private Clock $clock,
        private HealthCheckTableGenerator $tableGenerator,
    ) {
    }

    #[Auth]
    #[Route(path: '/admin/system/health', method: Method::GET, name: 'admin.system.health')]
    public function showDashboard(): ViewResult
    {
        error_log("HealthController: showDashboard called");

        // Debug: Log the health_checks data structure
        error_log("HealthController: Creating dummy health data...");

        // Create simple dummy health data for now
        $healthChecks = [
            [
                'componentName' => 'Framework',
                'statusText' => 'healthy',
                'statusClass' => 'success',
                'message' => 'Framework is running',
                'responseTime' => '12ms',
            ],
            [
                'componentName' => 'Database',
                'statusText' => 'healthy',
                'statusClass' => 'success',
                'message' => 'Connection successful',
                'responseTime' => '8ms',
            ],
            [
                'componentName' => 'Redis',
                'statusText' => 'healthy',
                'statusClass' => 'success',
                'message' => 'Cache operational',
                'responseTime' => '5ms',
            ],
        ];

        error_log("HealthController: health_checks first statusText: " . $healthChecks[0]['statusText']);
        error_log("HealthController: health_checks first statusClass: " . $healthChecks[0]['statusClass']);

        // Generate table using TableGenerator
        $healthCheckTable = $this->tableGenerator->generate($healthChecks);

        $data = [
            'title' => 'System Health',
            'overall_status' => 'HEALTHY',
            'health_checks' => $healthChecks,
            'health_check_table' => $healthCheckTable,
            'health_checks_count' => count($healthChecks),
            'total_checks' => count($healthChecks),
            'healthy_checks' => count($healthChecks),
            'warning_checks' => 0,
            'failed_checks' => 0,
            'current_year' => $this->clock->now()->format('Y'),
        ];

        $finalData = $this->layoutProcessor->processLayoutFromArray($data);

        error_log("HealthController: Final data keys: " . implode(', ', array_keys($finalData)));

        return new ViewResult(
            template: 'health-dashboard',
            metaData: new MetaData('System Health', 'System Health Dashboard'),
            data: $finalData
        );
    }

    #[Route('/admin/health-optimized', Method::GET)]
    public function showOptimizedDashboard(): ViewResult
    {
        // Get initial health data for view processors
        $healthReport = $this->healthManager->runAllChecks();

        $metaData = new MetaData(
            title: 'System Health Dashboard',
            description: 'Real-time system health monitoring'
        );

        // Prepare data for view processors
        $healthChecks = [];
        foreach ($healthReport->results as $componentName => $result) {
            $details = [];
            if (! empty($result->details)) {
                foreach ($result->details as $key => $value) {
                    $details[] = ['key' => $key, 'value' => is_scalar($value) ? (string)$value : json_encode($value)];
                }
            }

            $healthChecks[] = [
                'componentName' => $componentName,
                'status' => $result->status->value,
                'output' => $result->message,
                'details' => $details,
                'time' => $result->responseTime ? round($result->responseTime * 1000, 2) . 'ms' : null,
            ];
        }

        return new ViewResult('health-dashboard-optimized', $metaData, [
            'overall_status' => $healthReport->overallStatus->value,
            'health_checks' => $healthChecks,
            'is_loading' => false,
            'error_message' => null,
            'subtitle' => 'Real-time System Health Monitoring',
            'pageClass' => 'health-dashboard-page',
        ]);
    }

    #[Route('/admin/health/api/status', Method::GET)]
    /**
     * @return JsonResult<array{status: string, data: array<string, mixed>}>
     */
    public function getSystemStatus(): JsonResult
    {
        $report = $this->healthManager->runAllChecks();

        return new JsonResult([
            'status' => 'success',
            'data' => $report->toArray(),
        ]);
    }

    #[Route('/admin/health/api/check/{name}', Method::GET)]
    /**
     * @return JsonResult<array{status: string, data?: array{check_name: string, result: array<string, mixed>}, message?: string, available_checks?: array<int, string>}>
     */
    public function runSingleCheck(string $name): JsonResult
    {
        $result = $this->healthManager->runCheck($name);

        if ($result === null) {
            return new JsonResult([
                'status' => 'error',
                'message' => "Health check '{$name}' not found",
                'available_checks' => $this->healthManager->getRegisteredChecks(),
            ], \App\Framework\Http\Status::NOT_FOUND);
        }

        return new JsonResult([
            'status' => 'success',
            'data' => [
                'check_name' => $name,
                'result' => $result->toArray(),
            ],
        ]);
    }

    #[Route('/admin/health/api/category/{category}', Method::GET)]
    /**
     * @return JsonResult<array{status: string, data?: array{category: string, category_display: string, category_icon: string, report: array<string, mixed>}, message?: string, available_categories?: array<int, string>}>
     */
    public function getChecksByCategory(string $category): JsonResult
    {
        try {
            $categoryEnum = HealthCheckCategory::from($category);
            $report = $this->healthManager->runChecksByCategory($categoryEnum);

            return new JsonResult([
                'status' => 'success',
                'data' => [
                    'category' => $category,
                    'category_display' => $categoryEnum->getDisplayName(),
                    'category_icon' => $categoryEnum->getIcon(),
                    'report' => $report->toArray(),
                ],
            ]);

        } catch (\ValueError $e) {
            return new JsonResult([
                'status' => 'error',
                'message' => "Invalid category '{$category}'",
                'available_categories' => array_column(HealthCheckCategory::cases(), 'value'),
            ], \App\Framework\Http\Status::BAD_REQUEST);
        }
    }

    #[Route('/admin/health/api/summary', Method::GET)]
    /**
     * @return JsonResult<array{status: string, data: array{overall_status: string, overall_icon: string, overall_color: string, summary_text: string, quick_stats: array<string, int>, categories: array<string, mixed>, timestamp: int}}>
     */
    public function getHealthSummary(): JsonResult
    {
        $report = $this->healthManager->runAllChecks();
        $checksByCategory = $this->healthManager->getChecksByCategory();

        return new JsonResult([
            'status' => 'success',
            'data' => [
                'overall_status' => $report->overallStatus->value,
                'overall_icon' => $report->overallStatus->getIcon(),
                'overall_color' => $report->overallStatus->getColor(),
                'summary_text' => $report->getSummary(),
                'quick_stats' => [
                    'total_checks' => count($report->results),
                    'healthy' => count($report->getHealthyChecks()),
                    'warnings' => count($report->getWarningChecks()),
                    'failed' => count($report->getFailedChecks()),
                    'categories' => count($checksByCategory),
                ],
                'categories' => $checksByCategory,
                'timestamp' => time(),
            ],
        ]);
    }

    #[Route('/admin/health/api/run-all', Method::POST)]
    /**
     * @return JsonResult<array{status: string, message: string, data: array<string, mixed>}>
     */
    public function runAllChecks(): JsonResult
    {
        $report = $this->healthManager->runAllChecks();

        return new JsonResult([
            'status' => 'success',
            'message' => 'All health checks completed',
            'data' => $report->toArray(),
        ]);
    }
}
