<?php

namespace App\Filament\Widgets\Charts;

use App\Enums\VerificationStatus;
use App\Models\Company;
use App\Models\VerificationRequest;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;

class CompanyStatusChart extends ChartWidget
{
    use HasWidgetShield;

    protected ?string $heading = 'Status Verifikasi Perusahaan';

    protected static ?int $sort = 2;

    protected int|string|array $columnSpan = 1;

    protected ?string $pollingInterval = null;

    protected function getData(): array
    {
        $data = VerificationRequest::query()
            ->selectRaw('status, count(*) as total')
            ->groupBy('status')
            ->get();

        $notSubmittedCount = Company::doesntHave('verificationRequest')->count();

        $labels = ['Belum Mengajukan'];
        $counts = [$notSubmittedCount];
        $colors = ['#94a3b8']; // Slate 400

        foreach (VerificationStatus::cases() as $status) {
            $labels[] = $status->getLabel();
            $counts[] = $data->where('status', $status)->first()?->total ?? 0;
            $colors[] = match ($status) {
                VerificationStatus::PENDING => '#f59e0b', // Amber 500
                VerificationStatus::APPROVED => '#10b981', // Emerald 500
                VerificationStatus::NEED_REVISION => '#0ea5e9', // Sky 500
                VerificationStatus::REJECTED => '#f43f5e', // Rose 500
            };
        }

        return [
            'datasets' => [
                [
                    'label' => 'Jumlah Perusahaan',
                    'data' => $counts,
                    'backgroundColor' => $colors,
                ],
            ],
            'labels' => $labels,
        ];
    }

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