<?php

namespace App\Filament\Widgets;

use App\Models\Category;
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartWidget;

class ServicesByCategoryChart extends ApexChartWidget
{
    protected static ?string $chartId = 'servicesByCategoryChart';

    protected static ?string $heading = 'الخدمات حسب القسم';

    protected static ?string $subheading = 'عدد الخدمات في كل قسم';

    protected static ?int $sort = 5;

    protected ?string $pollingInterval = '60s';

    protected function getOptions(): array
    {
        $categories = Category::withCount('services')
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $labels = $categories->map(fn ($c) => $c->getTranslation('name', 'ar'))->toArray();
        $counts = $categories->pluck('services_count')->toArray();

        $colors = ['#f59e0b', '#3b82f6', '#10b981', '#8b5cf6', '#ef4444', '#ec4899', '#14b8a6'];

        return [
            'chart' => [
                'type' => 'bar',
                'height' => 320,
                'toolbar' => [
                    'show' => false,
                ],
            ],
            'series' => [
                [
                    'name' => 'عدد الخدمات',
                    'data' => $counts,
                ],
            ],
            'xaxis' => [
                'categories' => $labels,
                'labels' => [
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontWeight' => 600,
                        'fontSize' => '13px',
                    ],
                ],
            ],
            'yaxis' => [
                'labels' => [
                    'style' => [
                        'fontFamily' => 'inherit',
                    ],
                ],
            ],
            'colors' => array_slice($colors, 0, count($labels)),
            'plotOptions' => [
                'bar' => [
                    'borderRadius' => 8,
                    'columnWidth' => '50%',
                    'distributed' => true,
                    'dataLabels' => [
                        'position' => 'top',
                    ],
                ],
            ],
            'dataLabels' => [
                'enabled' => true,
                'offsetY' => -20,
                'style' => [
                    'fontFamily' => 'inherit',
                    'fontWeight' => 600,
                    'fontSize' => '14px',
                    'colors' => ['#374151'],
                ],
            ],
            'legend' => [
                'show' => false,
            ],
            'grid' => [
                'strokeDashArray' => 4,
            ],
        ];
    }
}

