<?php

namespace App\Filament\Widgets;

use App\Enums\BookingItemStatus;
use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use App\Models\Booking;
use App\Models\BookingItem;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class RevenueTrendsChart extends ChartWidget
{
    use InteractsWithPageFilters;

    public function getHeading(): string
    {
        return __('Revenue 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()->where('payment_status', PaymentStatus::PAID);
        $query = BookingItem::query()->whereNotIn('status', [BookingItemStatus::DECLINED, BookingItemStatus::CANCELED])
            ->whereHas('booking', function (Builder $query) {
                $query->where('status', BookingStatus::PAID);
            });

        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,
             SUM(commission) as revenue,
              SUM(price) as total_paid,
              COUNT(*) as count')
            ->groupBy('month')
            ->orderBy('month')
            ->get();

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

        return [
            'datasets' => [
                [
                    'label' => __('Revenue (SAR)'),
                    'data' => $data,
                    'borderColor' => '#10B981',
                    'backgroundColor' => '#10B981',
                    'fill' => false,
                    'yAxisID' => 'y',
                ],
                [
                    'label' => __('Money Paid (SAR)'),
                    'data' => $total_paid,
                    'borderColor' => '#EF4444',
                    'backgroundColor' => '#EF4444',
                    'fill' => false,
                    'yAxisID' => 'y',
                ],
                [
                    'label' => __('Number of Booking Items'),
                    'data' => $counts,
                    'borderColor' => '#3B82F6',
                    'backgroundColor' => '#3B82F6',
                    'fill' => false,
                    'yAxisID' => 'y1',
                ],
            ],
            'labels' => $labels,
        ];
    }

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

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