<?php

declare(strict_types=1);

namespace App\Filament\Widgets\Workspace;

use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

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

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

    protected ?string $pollingInterval = null;

    /**
     * @var array<int, array{
     *     key: string,
     *     label: string,
     *     value: int,
     *     category: string,
     *     description: string,
     *     destination: ?array<string, mixed>,
     *     destination_url: ?string,
     *     color: string,
     * }>
     */
    public array $metrics = [];

    /**
     * @param  array<int, array{
     *     key: string,
     *     label: string,
     *     value: int,
     *     category: string,
     *     description: string,
     *     destination: ?array<string, mixed>,
     *     destination_url: ?string,
     *     color: string,
     * }>  $metrics
     */
    public function mount(array $metrics = []): void
    {
        $this->metrics = $metrics;
    }

    /**
     * @return array<Stat>
     */
    protected function getStats(): array
    {
        return collect($this->metrics)
            ->map(function (array $metric): Stat {
                $stat = Stat::make($metric['label'], $metric['value'])
                    ->description($metric['description'])
                    ->color($metric['color']);

                $destination = $metric['destination'] ?? null;
                $destinationUrl = is_array($destination) && ($destination['disabled'] ?? false) === false
                    ? ($destination['url'] ?? null)
                    : ($metric['destination_url'] ?? null);

                if (is_string($destinationUrl) && $destinationUrl !== '') {
                    $stat->url($destinationUrl);
                }

                return $stat;
            })
            ->all();
    }
}
