<?php

namespace App\Filament\Widgets;

use App\Models\ImportedJob;
use Filament\Support\RawJs;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Str;

class JobsByCategoryChart extends ChartWidget
{
    protected static bool $isLazy = false;

    protected static ?int $sort = 4;

    protected ?string $heading = 'Active jobs by category';

    protected ?string $description = 'Current imported job mix across broad remote roles.';

    protected string $color = 'primary';

    protected int|string|array $columnSpan = 1;

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

    /**
     * @return array<string, mixed>
     */
    protected function getData(): array
    {
        $rows = ImportedJob::query()
            ->active()
            ->selectRaw('category, count(*) as total')
            ->groupBy('category')
            ->orderByDesc('total')
            ->limit(8)
            ->pluck('total', 'category');

        return [
            'datasets' => [
                [
                    'label' => 'Active jobs',
                    'data' => $rows->values()->all(),
                    'backgroundColor' => [
                        '#0f766e',
                        '#38bdf8',
                        '#10b981',
                        '#f59e0b',
                        '#64748b',
                        '#2563eb',
                        '#14b8a6',
                        '#94a3b8',
                    ],
                    'borderWidth' => 0,
                    'hoverOffset' => 8,
                ],
            ],
            'labels' => $rows->keys()
                ->map(fn (string $category): string => Str::of($category)->replace('-', ' ')->title()->toString())
                ->all(),
        ];
    }

    /**
     * @return array<string, mixed>|RawJs|null
     */
    protected function getOptions(): array|RawJs|null
    {
        return [
            'cutout' => '64%',
            'plugins' => [
                'legend' => [
                    'position' => 'bottom',
                    'labels' => [
                        'usePointStyle' => true,
                        'pointStyle' => 'circle',
                    ],
                ],
            ],
        ];
    }
}
