<?php

namespace App\Filament\Widgets;

use App\Models\ClickLog;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Carbon;

class AdminTrafficChart extends ChartWidget
{
    protected ?string $heading = 'Traffic Trends';

    protected ?string $description = 'Click volume from the last 14 days.';

    protected string $color = 'primary';

    protected ?string $pollingInterval = '10s';

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

    protected static ?int $sort = 2;

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

    /**
     * @return array<string, mixed>
     */
    protected function getData(): array
    {
        $start = now()->subDays(13)->startOfDay();

        $rawCounts = ClickLog::query()
            ->where('clicked_at', '>=', $start)
            ->selectRaw('DATE(clicked_at) as click_date, COUNT(*) as aggregate')
            ->groupBy('click_date')
            ->pluck('aggregate', 'click_date');

        $days = collect(range(0, 13))->map(fn (int $offset): Carbon => $start->copy()->addDays($offset));

        return [
            'datasets' => [
                [
                    'label' => 'Clicks',
                    'data' => $days->map(fn (Carbon $date): int => (int) ($rawCounts[$date->toDateString()] ?? 0))->all(),
                    'borderColor' => '#4648d4',
                    'backgroundColor' => 'rgba(70, 72, 212, 0.12)',
                    'fill' => true,
                    'tension' => 0.4,
                ],
            ],
            'labels' => $days->map(fn (Carbon $date): string => $date->format('M d'))->all(),
        ];
    }
}
