<?php

namespace App\Filament\Widgets;

use App\Enums\BookingItemStatus;
use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use App\Filament\Resources\AdminResource;
use App\Filament\Resources\BookingItemResource;
use App\Filament\Resources\BookingResource;
use App\Filament\Resources\CategoryResource;
use App\Filament\Resources\CityResource;
use App\Filament\Resources\ContactResource;
use App\Filament\Resources\NationalityResource;
use App\Filament\Resources\PackageResource;
use App\Filament\Resources\ReviewResource;
use App\Filament\Resources\RoleResource;
use App\Filament\Resources\ServiceProviderResource;
use App\Filament\Resources\ServiceResource;
use App\Filament\Resources\UserResource;
use App\Models\Booking;
use App\Models\BookingItem;
use App\Models\Category;
use App\Models\City;
use App\Models\Contact;
use App\Models\Nationality;
use App\Models\Payment;
use App\Models\Product;
use App\Models\Review;
use App\Models\ServiceProvider;
use App\Models\User;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Request;

class DashboardStatsOverview extends BaseWidget
{
    use InteractsWithPageFilters;
    protected int | string | array $columnSpan = 'full';

    protected function getStats(): array
    {
        // dd($this->filters);
        $dateFrom = $this->filters['date_from'] ? Carbon::parse($this->filters['date_from']) : null;
        $dateUntil = $this->filters['date_until'] ? Carbon::parse($this->filters['date_until']) : null;

        $scopeQuery = function ($model) use ($dateFrom, $dateUntil): Builder {
            $query = $model::query();
            if ($dateFrom) {
                $query->whereDate('created_at', '>=', $dateFrom);
            }
            if ($dateUntil) {
                $query->whereDate('created_at', '<=', $dateUntil);
            }
            return $query;
        };

        $payment_filter  = [];
        $payment_filter['tableFilters'] = [
            "status" => [
                "values" => [
                    BookingItemStatus::COMPLETED->value,
                    BookingItemStatus::PENDING->value,
                    BookingItemStatus::CONFIRMED->value,
                ]
            ],
            "booking" => [
                "status" => [
                    "value" => PaymentStatus::PAID->value
                ]
            ]
        ];

        $dateFilter = [];
        if ($dateFrom) {
            $dateFilter['tableFilters']['created_at']['created_from'] = $dateFrom->format('Y-m-d');
            $payment_filter['tableFilters']['created_at']['created_from'] = $dateFrom->format('Y-m-d');
        }
        if ($dateUntil) {
            $dateFilter['tableFilters']['created_at']['created_until'] = $dateUntil->format('Y-m-d');
            $payment_filter['tableFilters']['created_at']['created_until'] = $dateUntil->format('Y-m-d');
        }
        // $dateFilter = ['tableFilters' => $dateFilter];

        $adminQuery = DB::table('admins');
        if ($dateFrom) {
            $adminQuery->whereDate('created_at', '>=', $dateFrom);
        }
        if ($dateUntil) {
            $adminQuery->whereDate('created_at', '<=', $dateUntil);
        }

        $roleQuery = DB::table('roles');
        if ($dateFrom) {
            $roleQuery->whereDate('created_at', '>=', $dateFrom);
        }
        if ($dateUntil) {
            $roleQuery->whereDate('created_at', '<=', $dateUntil);
        }





        return [
            Stat::make(__('app.users'), $scopeQuery(new User())->withTrashed()->count() . ' (' . $scopeQuery(new User())->count() . ' ' . __('app.active') . ')')
                ->description(__('app.total_users_vs_active_users'))
                ->descriptionIcon('heroicon-m-users')
                ->color('success')
                ->url(UserResource::getUrl('index', $dateFilter)),
            Stat::make(__('app.service_providers'), $scopeQuery(new ServiceProvider())->count() . ' (' . $scopeQuery(new ServiceProvider())->where('is_active', true)->count() . ' ' . __('app.active') . ')')
                ->description(__('app.total_service_providers_vs_active_service_providers'))
                ->descriptionIcon('heroicon-m-briefcase')
                ->color('warning')
                ->url(ServiceProviderResource::getUrl('index', $dateFilter)),
            Stat::make(__('app.services'), $scopeQuery(new Product())->where('type', 'service')->count() . ' (' . $scopeQuery(new Product())->where('type', 'service')->scopes(['available'])->count() . ' ' . __('app.active') . ')')
                ->description(__('app.total_services_vs_active_services'))
                ->descriptionIcon('heroicon-m-cog')
                ->color('info')
                ->url(ServiceResource::getUrl('index', $dateFilter)),
            Stat::make(__('app.packages'), $scopeQuery(new Product())->where('type', 'package')->count() . ' (' . $scopeQuery(new Product())->where('type', 'package')->scopes(['available'])->count() . ' ' . __('app.active') . ')')
                ->description(__('app.total_packages_vs_active_packages'))
                ->descriptionIcon('heroicon-m-gift')
                ->color('info')
                ->url(PackageResource::getUrl('index', $dateFilter)),
            // Stat::make(__('app.categories'), $scopeQuery(new Category())->count() . ' (' . $scopeQuery(new Category())->where('is_active', true)->count() . ' ' . __('app.active') . ')')
            //     ->description(__('app.total_categories_vs_active_categories'))
            //     ->descriptionIcon('heroicon-m-tag')
            //     ->color('gray')
            //     ->url(CategoryResource::getUrl('index', $dateFilter)),
            // Stat::make(__('app.cities'), $scopeQuery(new City())->count() . ' (' . $scopeQuery(new City())->where('is_active', true)->count() . ' ' . __('app.active') . ')')
            //     ->description(__('app.total_cities_vs_active_cities'))
            //     ->descriptionIcon('heroicon-m-map-pin')
            //     ->color('gray')
            //     ->url(CityResource::getUrl('index', $dateFilter)),
            Stat::make(__('app.bookings'), $scopeQuery(new Booking())->count() . ' (' . $scopeQuery(new Booking())->where('status', BookingStatus::PAID)->count() . ' ' . __('app.paid') . ')')
                ->description(__('app.total_bookings_vs_paid_bookings'))
                ->descriptionIcon('heroicon-m-calendar')
                ->color('danger')
                ->url(BookingResource::getUrl('index', $dateFilter)),
            Stat::make(__('app.revenue'), 'SAR ' . number_format(
                $scopeQuery(new BookingItem())
                    ->whereNotIn('status', [BookingItemStatus::DECLINED, BookingItemStatus::CANCELED])
                    ->whereHas('booking', function (Builder $query) {
                        $query->where('status', BookingStatus::PAID);
                    })
                    ->sum('price'),
                2
            ) . ' (' . 'SAR ' . number_format(
                $scopeQuery(new BookingItem())
                    ->whereNotIn('status', [BookingItemStatus::DECLINED, BookingItemStatus::CANCELED])
                    ->whereHas('booking', function (Builder $query) {
                        $query->where('status', BookingStatus::PAID);
                    })->sum('commission'),
                2
            ) . ' ' . __('app.net') . ')')
                ->description(__('app.total_revenue_vs_net_revenue'))
                ->descriptionIcon('heroicon-m-currency-dollar')
                ->color('success')
                ->url(BookingItemResource::getUrl('index', $payment_filter)),
            Stat::make(__('app.contacts'), $scopeQuery(new Contact())->count() . ' (' . $scopeQuery(new Contact())->where('is_resolved', false)->count() . ' ' . __('app.unresolved') . ')')
                ->description(__('app.total_contacts_vs_unresolved_contacts'))
                ->descriptionIcon('heroicon-m-envelope')
                ->color('secondary')
                ->url(ContactResource::getUrl('index', $dateFilter)),
            Stat::make(__('app.reviews'), $scopeQuery(new Review())->count() . ' (' . number_format($scopeQuery(new Review())->avg('rating'), 2) . ' ' . __('app.avg_rating') . ')')
                ->description(__('app.total_reviews_vs_average_rating'))
                ->descriptionIcon('heroicon-m-star')
                ->color('warning')
                ->url(ReviewResource::getUrl('index', $dateFilter)),
        ];
    }
}
