<?php

namespace App\Filament\Widgets;

use App\Models\DeliveryPartner;
use App\Models\DeliveryPartnerApplication;
use App\Models\Order;
use App\Models\Vendor;
use App\Models\VendorApplication;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class StatsOverview extends StatsOverviewWidget
{
    protected ?string $heading = 'Today at a glance';

    protected ?string $pollingInterval = '60s';

    protected static ?int $sort = 1;

    protected function getStats(): array
    {
        $todayGmv = (float) Order::whereDate('created_at', today())
            ->where('status', '!=', 'cancelled')
            ->sum('grand_total');

        $todayOrders = Order::whereDate('created_at', today())->count();

        $weekGmv = (float) Order::where('created_at', '>=', now()->startOfWeek())
            ->where('status', '!=', 'cancelled')
            ->sum('grand_total');

        $pendingVendorApps    = VendorApplication::whereIn('status', ['submitted', 'under_review'])->count();
        $pendingDeliveryApps  = DeliveryPartnerApplication::whereIn('status', ['submitted', 'under_review'])->count();
        $activeVendors        = Vendor::where('status', 'active')->count();
        $onlinePartners       = DeliveryPartner::where('status', 'active')->where('is_online', true)->count();
        $totalActivePartners  = DeliveryPartner::where('status', 'active')->count();

        return [
            Stat::make('Today\'s Orders', number_format($todayOrders))
                ->description('PKR ' . number_format($todayGmv, 0) . ' GMV')
                ->descriptionIcon('heroicon-m-arrow-trending-up')
                ->color('success')
                ->chart($this->ordersChartLast7Days()),

            Stat::make('Week-to-date GMV', 'PKR ' . number_format($weekGmv, 0))
                ->description('Since Monday')
                ->descriptionIcon('heroicon-m-calendar-days')
                ->color('info'),

            Stat::make('Pending Applications', $pendingVendorApps + $pendingDeliveryApps)
                ->description("{$pendingVendorApps} vendor · {$pendingDeliveryApps} delivery")
                ->descriptionIcon('heroicon-m-clipboard-document-list')
                ->color($pendingVendorApps + $pendingDeliveryApps > 0 ? 'warning' : 'gray'),

            Stat::make('Active Vendors', number_format($activeVendors))
                ->description("{$onlinePartners} of {$totalActivePartners} partners online")
                ->descriptionIcon('heroicon-m-building-storefront')
                ->color('primary'),
        ];
    }

    /** Quick spark-line: orders per day for last 7 days. */
    private function ordersChartLast7Days(): array
    {
        return collect(range(6, 0))
            ->map(fn($daysAgo) => Order::whereDate('created_at', today()->subDays($daysAgo))->count())
            ->toArray();
    }
}
