<?php

namespace App\Filament\Widgets;

use App\Models\AssessmentAttempt;
use Filament\Widgets\ChartWidget;

class AttemptsChart extends ChartWidget
{
    protected ?string $heading = 'Assessment activity, last 30 days';

    protected int|string|array $columnSpan = 1;

    protected static ?int $sort = -3;

    protected function getData(): array
    {
        $days = collect(range(29, 0))
            ->map(fn (int $daysAgo) => now()->subDays($daysAgo)->startOfDay());

        $counts = AssessmentAttempt::where('status', 'completed')
            ->where('completed_at', '>=', now()->subDays(30)->startOfDay())
            ->get()
            ->groupBy(fn ($attempt) => $attempt->completed_at->format('Y-m-d'))
            ->map->count();

        return [
            'datasets' => [
                [
                    'label' => 'Completed assessments',
                    'data' => $days->map(fn ($day) => $counts[$day->format('Y-m-d')] ?? 0)->values()->all(),
                    'borderColor' => '#58b9e6',
                    'backgroundColor' => 'rgba(88, 185, 230, 0.15)',
                    'fill' => true,
                    'tension' => 0.35,
                ],
            ],
            'labels' => $days->map(fn ($day) => $day->format('j M'))->values()->all(),
        ];
    }

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