<?php

declare(strict_types=1);

namespace App\Filament\System\Widgets;

use App\Support\ProductTelemetry\ProductTelemetrySummaryQuery;
use App\Support\SystemConsole\SystemConsoleWindow;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

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

    protected ?string $heading = 'Product telemetry';

    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';
        $summary = app(ProductTelemetrySummaryQuery::class)->summarize($window->startAt(), now());

        $stats = [
            Stat::make('Active workspaces', $summary['active_workspaces'])
                ->description($summary['total_events'] > 0
                    ? sprintf('%d events in %s', $summary['total_events'], $windowLabel)
                    : sprintf('No telemetry recorded in %s.', $windowLabel))
                ->color($summary['active_workspaces'] > 0 ? 'primary' : 'gray'),
        ];

        foreach ($summary['families'] as $family) {
            $stats[] = Stat::make($family['label'], $family['count'])
                ->description($windowLabel)
                ->color($family['count'] > 0 ? 'primary' : 'gray');
        }

        return $stats;
    }
}