<?php

namespace App\Filament\Widgets;

use App\Models\Category;
use App\Models\Product;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

class TopCategoriesBarChart extends ChartWidget
{
    use InteractsWithPageFilters;

    public function getHeading(): string
    {
        return __('Top Categories by Services');
    }

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

    protected function getFilters(): ?array
    {
        return [];
    }

    protected function getData(): array
    {
        $dateFrom = $this->filters['date_from'] ?? null;
        $dateUntil = $this->filters['date_until'] ?? null;

        $query = Category::query()
            ->withCount('products')
            ->orderByDesc('products_count')
            ->limit(10);

        if ($dateFrom) {
            $query->whereHas('products', fn($q) => $q->whereDate('created_at', '>=', Carbon::parse($dateFrom)));
        }

        if ($dateUntil) {
            $query->whereHas('products', fn($q) => $q->whereDate('created_at', '<=', Carbon::parse($dateUntil)));
        }

        $topCategories = $query->get();
        $topCategories = $topCategories->filter(fn($category) => $category->products_count > 0);

        $labels = $topCategories->pluck('name_' . app()->getLocale())
            // ->map(fn($name) => Str::limit($name, 20))
            ->toArray();
        $data = $topCategories->pluck('products_count')->toArray();

        return [
            'datasets' => [
                [
                    'label' => __('Number of Services'),
                    'data' => $data,
                    'backgroundColor' => '#8B5CF6',
                ],
            ],
            'labels' => $labels,
        ];
    }

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

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'legend' => [
                    'display' => false,
                ],
            ],
            'scales' => [
                'y' => [
                    'beginAtZero' => true,
                ],
                'x' => [
                    'ticks' => [
                        'display' => false,
                    ],
                ],
            ],
        ];
    }
}
