<?php

namespace App\Filament\Widgets;

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

class BookingTrendsChart extends ChartWidget
{
    use InteractsWithPageFilters;

    public function getHeading(): string
    {
        return __('Booking Trends Over Time');
    }

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

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

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

        $dateRange = $query->clone()
            ->selectRaw('DATE_FORMAT(created_at, "%Y-%m") as month, COUNT(*) as count')
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        $labels = $dateRange->pluck('month')->toArray();
        $data = $dateRange->pluck('count')->toArray();

        return [
            'datasets' => [
                [
                    'label' => __('Bookings'),
                    'data' => $data,
                    'borderColor' => '#EF4444',
                    'backgroundColor' => '#EF4444',
                    'fill' => true,
                ],
            ],
            'labels' => $labels,
        ];
    }

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

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