<?php

namespace App\Filament\Widgets;

use App\Filament\Concerns\CachesWidgetData;
use App\Models\AssistanceApplication;
use App\Models\Setting;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Carbon;

class AssistanceApplicationsChart extends ChartWidget
{
    use CachesWidgetData;

    protected ?string $heading = 'Assistance';

    protected function getCacheTtl(): int
    {
        return 300;
    }

    public static function canView(): bool
    {
        return Setting::get('enable_assistance_applications', true);
    }

    protected function getData(): array
    {
        $data = $this->cached('monthly_data', fn () => $this->getApplicationsPerMonth());

        return [
            'datasets' => [
                [
                    'label' => 'Assistance Applications',
                    'data' => $data['counts'],
                    'borderColor' => 'rgb(168, 85, 247)',
                    'backgroundColor' => 'rgba(168, 85, 247, 0.1)',
                    'tension' => 0.4,
                ],
            ],
            'labels' => $data['labels'],
        ];
    }

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

    /**
     * @return array{labels: array<string>, counts: array<int>}
     */
    protected function getApplicationsPerMonth(): array
    {
        $now = Carbon::now();
        $months = [];
        $labels = [];
        $counts = [];

        for ($i = 11; $i >= 0; $i--) {
            $date = $now->copy()->subMonths($i);
            $months[] = $date->format('Y-m');
            $labels[] = $date->format('M Y');
        }

        $applications = AssistanceApplication::query()
            ->where('created_at', '>=', $now->copy()->subMonths(11)->startOfMonth())
            ->get()
            ->groupBy(fn ($application) => Carbon::parse($application->created_at)->format('Y-m'));

        foreach ($months as $month) {
            $counts[] = $applications->get($month)?->count() ?? 0;
        }

        return [
            'labels' => $labels,
            'counts' => $counts,
        ];
    }
}
