<?php

declare(strict_types=1);

namespace App\Filament\System\Widgets;

use App\Support\CustomerHealth\WorkspaceHealthSummaryQuery;
use App\Support\SystemConsole\SystemConsoleWindow;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class CustomerHealthKpis extends StatsOverviewWidget
{
    protected static bool $isLazy = false;

    protected ?string $heading = 'Customer health';

    protected int|string|array $columnSpan = 'full';

    public ?string $window = null;

    /**
     * @return array<Stat>
     */
    protected function getStats(): array
    {
        $window = SystemConsoleWindow::fromNullable($this->window ?? (string) request()->query('window'));
        $windowLabel = SystemConsoleWindow::options()[$window->value] ?? 'Last 24 hours';
        $counts = app(WorkspaceHealthSummaryQuery::class)->healthCounts($window);

        return [
            Stat::make('Healthy', $counts['ok'])
                ->description(sprintf('Operational stability, review-pack readiness, and engagement freshness honor %s.', $windowLabel))
                ->color($counts['ok'] > 0 ? 'success' : 'gray'),
            Stat::make('Warning', $counts['warn'])
                ->description('Onboarding readiness, provider health, and governance pressure stay point-in-time.')
                ->color($counts['warn'] > 0 ? 'warning' : 'gray'),
            Stat::make('Critical', $counts['critical'])
                ->description('Overall workspace health is derived from existing system truth only.')
                ->color($counts['critical'] > 0 ? 'danger' : 'gray'),
            Stat::make('Unknown', $counts['unknown'])
                ->description('Missing or stale inputs stay explicit instead of silently reading healthy.')
                ->color('gray'),
        ];
    }
}