<?php

namespace App\Filament\Widgets;

use App\Models\Lead;
use Filament\Widgets\ChartWidget;

class LeadsBySourceChart extends ChartWidget
{
    protected ?string $heading = 'Leads by source';

    protected int|string|array $columnSpan = ['md' => 2, 'xl' => 6];

    protected static ?int $sort = -2;

    protected function getData(): array
    {
        $bySource = Lead::query()
            ->selectRaw("COALESCE(source, 'other') as source, COUNT(*) as total")
            ->groupBy('source')
            ->pluck('total', 'source');

        $palette = ['#1c2b5f', '#58b9e6', '#2787b8', '#6a82c4', '#8ed4f2', '#28366a'];

        return [
            'datasets' => [[
                'label' => 'Leads',
                'data' => $bySource->values()->all(),
                'backgroundColor' => collect($bySource)->keys()
                    ->map(fn ($_, $i) => $palette[$i % count($palette)])->all(),
                'borderWidth' => 0,
            ]],
            'labels' => $bySource->keys()->map(fn ($s) => ucfirst((string) $s))->all(),
        ];
    }

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

    protected function getOptions(): array
    {
        return [
            'plugins' => ['legend' => ['position' => 'bottom']],
        ];
    }
}
