<?php

namespace App\Filament\Widgets;

use App\Enums\CooperationStatus;
use App\Models\Cooperation;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;

class CooperationStatusChart extends ChartWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected ?string $heading = 'Status Kerjasama';

    protected static ?int $sort = 9;

    protected int|string|array $columnSpan = 1;

    protected function getData(): array
    {
        $startDate = $this->filters['startDate'] ?? null;
        $endDate = $this->filters['endDate'] ?? null;

        $data = Cooperation::query()
            ->when($startDate, fn ($q) => $q->whereDate('created_at', '>=', $startDate))
            ->when($endDate, fn ($q) => $q->whereDate('created_at', '<=', $endDate))
            ->selectRaw('status, count(*) as total')
            ->groupBy('status')
            ->get();

        $labels = [];
        $counts = [];
        $colors = [];

        foreach (CooperationStatus::cases() as $case) {
            $labels[] = $case->getLabel();
            $counts[] = $data->where('status', $case)->first()?->total ?? 0;
            $colors[] = match ($case) {
                CooperationStatus::PENDING => '#F59E0B',
                CooperationStatus::ASSIGNMENT => '#3B82F6',
                CooperationStatus::VERIFICATION => '#6366F1',
                CooperationStatus::PAYMENT => '#8B5CF6',
                CooperationStatus::COMPLETED => '#10B981',
            };
        }

        return [
            'datasets' => [
                [
                    'label' => 'Jumlah Kerjasama',
                    'data' => $counts,
                    'backgroundColor' => $colors,
                ],
            ],
            'labels' => $labels,
        ];
    }

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