<?php

namespace App\Filament\Association\Widgets;

use App\Services\ReportingService;
use Filament\Widgets\ChartWidget;

class RevenueByCategoryChart extends ChartWidget
{
    protected static ?string $heading = 'Revenue by Category';

    protected static ?int $sort = 4;

    protected int | string | array $columnSpan = 1;

    protected function getData(): array
    {
        $associationId = filament()->getTenant()->id;
        $reportingService = app(ReportingService::class);

        $dateFrom = now()->subMonths(12)->startOfMonth()->toDateString();
        $data = $reportingService->getRevenueByCategory($associationId, $dateFrom);

        $colors = [
            'rgba(59, 130, 246, 0.8)',   // blue
            'rgba(34, 197, 94, 0.8)',    // green
            'rgba(168, 85, 247, 0.8)',   // purple
            'rgba(249, 115, 22, 0.8)',   // orange
            'rgba(239, 68, 68, 0.8)',    // red
            'rgba(99, 102, 241, 0.8)',   // indigo
            'rgba(20, 184, 166, 0.8)',   // teal
            'rgba(245, 158, 11, 0.8)',   // amber
        ];

        $borderColors = [
            'rgb(59, 130, 246)',
            'rgb(34, 197, 94)',
            'rgb(168, 85, 247)',
            'rgb(249, 115, 22)',
            'rgb(239, 68, 68)',
            'rgb(99, 102, 241)',
            'rgb(20, 184, 166)',
            'rgb(245, 158, 11)',
        ];

        return [
            'datasets' => [
                [
                    'data' => collect($data)->pluck('total')->toArray(),
                    'backgroundColor' => array_slice($colors, 0, count($data)),
                    'borderColor' => array_slice($borderColors, 0, count($data)),
                    'borderWidth' => 1,
                ],
            ],
            'labels' => collect($data)->pluck('label')->toArray(),
        ];
    }

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

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'legend' => [
                    'position' => 'bottom',
                ],
            ],
        ];
    }
}
