<?php

namespace App\Filament\Widgets;

use App\Models\Review;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Illuminate\Support\Carbon;

class ReviewRatingBarChart extends ChartWidget
{
    use InteractsWithPageFilters;

    public function getHeading(): string
    {
        return __('Review Ratings Distribution');
    }

    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 = Review::query();

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

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

        $ratingCounts = $query->clone()
            ->selectRaw('rating, COUNT(*) as count')
            ->groupBy('rating')
            ->pluck('count', 'rating')
            ->toArray();

        $labels = [];
        $data = [];
        $colors = [
            1 => '#EF4444',
            2 => '#F59E0B',
            3 => '#FBBF24',
            4 => '#10B981',
            5 => '#059669',
        ];

        for ($i = 1; $i <= 5; $i++) {
            $labels[] = trans_choice('{1} :count Star|[2,*] :count Stars', $i, ['count' => $i]);
            $data[] = $ratingCounts[$i] ?? 0;
        }

        return [
            'datasets' => [
                [
                    'label' => __('Number of Reviews'),
                    'data' => $data,
                    'backgroundColor' => array_values($colors),
                ],
            ],
            'labels' => $labels,
        ];
    }

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

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