<?php

namespace App\Filament\Widgets;

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

class ApplicationsChart extends ChartWidget
{
    use CachesWidgetData;

    protected ?string $heading = 'Adoptions';

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

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

        return [
            'datasets' => [
                [
                    'label' => 'Pets Adopted',
                    'data' => $data['counts'],
                    'borderColor' => 'rgb(59, 130, 246)',
                    'backgroundColor' => 'rgba(59, 130, 246, 0.1)',
                    'tension' => 0.4,
                ],
            ],
            'labels' => $data['labels'],
        ];
    }

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

    /**
     * @return array{labels: array<string>, counts: array<int>}
     */
    protected function getAdoptionsPerMonth(): 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('status', 'adopted')
            ->whereNotNull('adoption_date')
            ->where('adoption_date', '>=', $now->copy()->subMonths(11)->startOfMonth())
            ->get()
            ->groupBy(fn ($pet) => Carbon::parse($pet->adoption_date)->format('Y-m'));

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

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