<?php

namespace App\Filament\Widgets\Charts;

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

class IssueDepartmentChart extends ChartWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected ?string $heading = 'Sebaran Isu Berdasarkan Perangkat Daerah';

    protected static ?int $sort = 16;

    protected int|string|array $columnSpan = 1;

    protected ?string $pollingInterval = null;

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

        $issueTable = (new IssueManagement)->getTable();
        $departmentTable = (new Department)->getTable();
        $pivotTable = 'department_issue_management';

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

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

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