<?php

namespace App\Filament\Widgets;

use App\Enums\MediaType;
use App\Models\PartnerMedia;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;

class MediaTypeChart extends ChartWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected ?string $heading = 'Distribusi Jenis Media';

    protected static ?int $sort = 2;

    protected int|string|array $columnSpan = 1;

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

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

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

        foreach (MediaType::cases() as $case) {
            $labels[] = $case->getLabel();
            $counts[] = $data->where('type', $case)->first()?->total ?? 0;
        }

        return [
            'datasets' => [
                [
                    'label' => 'Jumlah Media',
                    'data' => $counts,
                    'backgroundColor' => [
                        '#36A2EB',
                        '#FF6384',
                        '#FFCE56',
                        '#4BC0C0',
                    ],
                ],
            ],
            'labels' => $labels,
        ];
    }

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