<?php

namespace App\Filament\Widgets;

use App\Models\ToolResult;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Str;

class ToolUsageChart extends ChartWidget
{
    protected ?string $heading = 'Most-used tools';

    protected int|string|array $columnSpan = ['md' => 2, 'xl' => 6];

    protected static ?int $sort = -1;

    protected function getData(): array
    {
        $byTool = ToolResult::query()
            ->selectRaw('tool, COUNT(*) as total')
            ->groupBy('tool')
            ->orderByDesc('total')
            ->limit(10)
            ->pluck('total', 'tool');

        return [
            'datasets' => [[
                'label' => 'Sessions saved',
                'data' => $byTool->values()->all(),
                'backgroundColor' => 'rgba(88, 185, 230, 0.55)',
                'borderColor' => '#2787b8',
                'borderRadius' => 4,
            ]],
            'labels' => $byTool->keys()
                ->map(fn ($t) => Str::headline((string) $t))->all(),
        ];
    }

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

    protected function getOptions(): array
    {
        return [
            'indexAxis' => 'y',
            'plugins' => ['legend' => ['display' => false]],
        ];
    }
}
