<?php

namespace App\Filament\Widgets;

use Filament\Widgets\ChartWidget;
use Functional\Tracking\Models\SetLog;

/**
 * Top 8 des exercices les plus loggés (nombre de séries), tous utilisateurs confondus.
 */
class TopExercisesChart extends ChartWidget
{
    protected static ?int $sort = 5;

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

    private const TOP_COUNT = 8;

    public function getHeading(): string
    {
        return 'Top 8 des exercices les plus loggés';
    }

    protected function getData(): array
    {
        $topExercises = SetLog::query()
            ->join('exercises', 'exercises.id', '=', 'set_logs.exercise_id')
            ->selectRaw('exercises.name as name, COUNT(*) as total')
            ->groupBy('exercises.id', 'exercises.name')
            ->orderByDesc('total')
            ->limit(self::TOP_COUNT)
            ->get();

        return [
            'datasets' => [
                [
                    'label' => 'Séries loguées',
                    'data' => $topExercises->pluck('total')->all(),
                    'backgroundColor' => '#f97316',
                    'borderRadius' => 4,
                ],
            ],
            'labels' => $topExercises->pluck('name')->all(),
        ];
    }

    protected function getType(): string
    {
        return 'bar';
    }
}
