<?php

namespace App\Filament\Widgets;

use App\Models\IssueManagement;
use App\Models\Location;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Illuminate\Support\Facades\DB;

class IssueLocationChart extends ChartWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected ?string $heading = 'Sebaran Isu Berdasarkan Wilayah';

    protected static ?int $sort = 15;

    protected int|string|array $columnSpan = 1;

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

        $issueTable = (new IssueManagement)->getTable();
        $locationTable = (new Location)->getTable();

        $data = IssueManagement::query()
            ->join($locationTable, "{$issueTable}.location_id", '=', "{$locationTable}.id")
            ->when($startDate, fn ($q) => $q->whereDate("{$issueTable}.created_at", '>=', $startDate))
            ->when($endDate, fn ($q) => $q->whereDate("{$issueTable}.created_at", '<=', $endDate))
            ->select("{$locationTable}.name", DB::raw('count(*) as total'))
            ->groupBy("{$locationTable}.id", "{$locationTable}.name")
            ->orderByDesc('total')
            ->limit(10)
            ->get();

        return [
            'datasets' => [
                [
                    'label' => 'Jumlah Isu',
                    'data' => $data->pluck('total')->toArray(),
                    'backgroundColor' => [
                        '#6366F1',
                        '#8B5CF6',
                        '#EC4899',
                        '#F43F5E',
                        '#F59E0B',
                        '#10B981',
                        '#06B6D4',
                        '#3B82F6',
                        '#6366F1',
                        '#8B5CF6',
                    ],
                ],
            ],
            'labels' => $data->pluck('name')->toArray(),
        ];
    }

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