<?php

namespace App\Filament\Widgets;

use App\Models\Booking;
use App\Models\ServiceProvider;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class TopServiceProvidersBarChart extends ChartWidget
{
    use InteractsWithPageFilters;

    public function getHeading(): string
    {
        return __('Top Service Providers by Bookings');
    }

    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 = ServiceProvider::query()
            ->withCount('bookingItems')
            ->orderByDesc('booking_items_count')
            ->limit(10);

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

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

        $topProviders = $query->get();
        $topProviders = $topProviders->filter(fn($provider) => $provider->booking_items_count > 0);

        $labels = $topProviders->pluck('name')
            ->toArray();
        $data = $topProviders->pluck('booking_items_count')->toArray();

        return [
            'datasets' => [
                [
                    'label' => __('Number of Bookings'),
                    'data' => $data,
                    'backgroundColor' => '#06B6D4',
                ],
            ],
            '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,
                    ],
                ],
            ],
        ];
    }
}
