<?php

namespace App\Filament\Widgets;

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

class PetIntakesChart extends ChartWidget
{
    use CachesWidgetData;

    protected ?string $heading = 'Pet Intakes';

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

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

        return [
            'datasets' => [
                [
                    'label' => 'Pet Intakes',
                    'data' => $data['counts'],
                    'backgroundColor' => 'rgba(249, 115, 22, 0.8)',
                    'borderColor' => 'rgb(249, 115, 22)',
                ],
            ],
            'labels' => $data['labels'],
        ];
    }

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

    /**
     * @return array{labels: array<string>, counts: array<int>}
     */
    protected function getIntakesPerMonth(): 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');
        }

        $pets = Pet::query()
            ->where('created_at', '>=', $now->copy()->subMonths(11)->startOfMonth())
            ->get()
            ->groupBy(fn ($pet) => $pet->created_at->format('Y-m'));

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

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