<?php

namespace App\Filament\Pages;

use App\Services\Core\HealthCheckService;
use App\Services\Core\ConfigurationManager;
use Filament\Pages\Page;
use Filament\Actions\Action;
use Illuminate\Support\Facades\Cache;

class SystemMonitoring extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-heart';

    protected static ?string $navigationGroup = 'System';

    protected static ?int $navigationSort = 2;

    protected static string $view = 'filament.pages.system-monitoring';

    protected static ?string $navigationLabel = 'System Monitoring';

    protected static ?string $title = 'System Health Dashboard';

    public array $healthData = [];

    public bool $autoRefresh = false;

    public function mount(): void
    {
        $this->loadHealthData();
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('refresh')
                ->label('Refresh Now')
                ->icon('heroicon-m-arrow-path')
                ->action('refreshHealthData'),
            
            Action::make('toggle_auto_refresh')
                ->label(fn () => $this->autoRefresh ? 'Disable Auto Refresh' : 'Enable Auto Refresh')
                ->icon(fn () => $this->autoRefresh ? 'heroicon-m-pause' : 'heroicon-m-play')
                ->action('toggleAutoRefresh'),
        ];
    }

    public function refreshHealthData(): void
    {
        // Clear cache to force fresh check
        Cache::forget('health_check_results');
        $this->loadHealthData();
        
        $this->dispatch('health-data-refreshed');
        $this->dispatch('notify', message: 'Health data refreshed successfully');
    }

    public function toggleAutoRefresh(): void
    {
        $this->autoRefresh = !$this->autoRefresh;
        
        if ($this->autoRefresh) {
            $this->dispatch('start-auto-refresh');
            $this->dispatch('notify', message: 'Auto refresh enabled (30 seconds interval)');
        } else {
            $this->dispatch('stop-auto-refresh');
            $this->dispatch('notify', message: 'Auto refresh disabled');
        }
    }

    private function loadHealthData(): void
    {
        try {
            $healthService = app(HealthCheckService::class);
            
            // Cache results for 30 seconds to avoid excessive checks
            $this->healthData = Cache::remember(
                'health_check_results',
                30,
                fn () => $healthService->runAllChecks()
            );
        } catch (\Throwable $e) {
            $this->healthData = [
                'overall_status' => 'error',
                'checks' => [],
                'summary' => ['total_checks' => 0, 'healthy' => 0, 'warning' => 0, 'error' => 1],
                'error_message' => $e->getMessage(),
            ];
        }
    }

    public function getOverallStatus(): string
    {
        return $this->healthData['overall_status'] ?? 'unknown';
    }

    public function getOverallStatusColor(): string
    {
        return match ($this->getOverallStatus()) {
            'healthy' => 'success',
            'warning' => 'warning',
            'error' => 'danger',
            default => 'gray',
        };
    }

    public function getSummary(): array
    {
        return $this->healthData['summary'] ?? [
            'total_checks' => 0,
            'healthy' => 0,
            'warning' => 0,
            'error' => 0,
        ];
    }

    public function getChecks(): array
    {
        return $this->healthData['checks'] ?? [];
    }

    public function getCheckStatusColor(string $status): string
    {
        return match ($status) {
            'healthy' => 'success',
            'warning' => 'warning',
            'error' => 'danger',
            default => 'gray',
        };
    }

    public function getCheckStatusIcon(string $status): string
    {
        return match ($status) {
            'healthy' => 'heroicon-o-check-circle',
            'warning' => 'heroicon-o-exclamation-triangle',
            'error' => 'heroicon-o-x-circle',
            default => 'heroicon-o-question-mark-circle',
        };
    }

    public function getSystemMetrics(): array
    {
        $checks = $this->getChecks();
        $metrics = [];

        // Database metrics
        if (isset($checks['database']['details'])) {
            $dbDetails = $checks['database']['details'];
            $metrics['database'] = [
                'connection_time' => $dbDetails['connection_time_ms'] ?? 0,
                'total_users' => $dbDetails['total_users'] ?? 0,
                'active_users_24h' => $dbDetails['active_users_24h'] ?? 0,
            ];
        }

        // System resources
        if (isset($checks['system_resources']['details'])) {
            $sysDetails = $checks['system_resources']['details'];
            $metrics['system'] = [
                'memory_usage_mb' => $sysDetails['memory_usage_mb'] ?? 0,
                'memory_usage_percent' => $sysDetails['memory_usage_percent'] ?? 0,
                'php_version' => $sysDetails['php_version'] ?? 'Unknown',
            ];
        }

        // Storage metrics
        if (isset($checks['storage']['details'])) {
            $storageDetails = $checks['storage']['details'];
            $metrics['storage'] = [
                'free_space_gb' => $storageDetails['free_space_gb'] ?? 0,
                'usage_percent' => $storageDetails['usage_percent'] ?? 0,
            ];
        }

        return $metrics;
    }

    public static function canAccess(): bool
    {
        // Only allow admin users to access monitoring
        return auth()->user()?->role === 'admin';
    }
}