<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Number;

class OrdersDashboardStatsOverview extends BaseWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    public static ?int $sort = 1;

    public function getHeading(): string
    {
        return __('pages.orders_dashboard').' - '.__('widgets.total_orders');
    }

    protected function getStats(): array
    {
        // Get filter value
        $selectedYear = $this->filters['year'] ?? null;
        $selectedProjectType = $this->filters['project_type'] ?? null;

        // Build base query with year filter
        $query = Order::query()->filterByTypePermissions();
        if ($selectedYear) {
            $query->whereYear('created_at', $selectedYear);
        }

        if ($selectedProjectType) {
            $query->where('type', $selectedProjectType);
        }

        $totalOrders = (clone $query)->count();
        $approvedOrders = (clone $query)->where('status', Order::STATUS_ACCEPTED)->count();
        $rejectedOrders = (clone $query)->where('status', Order::STATUS_REJECTED)->count();
        $underProcessingOrders = (clone $query)->whereNotIn('status', [Order::STATUS_ACCEPTED, Order::STATUS_REJECTED])->count();

        return [
            Stat::make(__('widgets.total_orders'), Number::format($totalOrders))
                ->description($selectedYear ? __('widgets.total_orders_in_year', ['year' => $selectedYear]) : __('widgets.all_orders_description'))
                ->descriptionIcon('heroicon-m-document-text')
                ->color('primary'),

            Stat::make(__('widgets.approved_orders'), Number::format($approvedOrders))
                ->description($selectedYear ? __('widgets.approved_orders_in_year', ['year' => $selectedYear]) : __('widgets.approved_orders_description'))
                ->descriptionIcon('heroicon-m-check-circle')
                ->color('success'),

            Stat::make(__('widgets.rejected_orders'), Number::format($rejectedOrders))
                ->description($selectedYear ? __('widgets.rejected_orders_in_year', ['year' => $selectedYear]) : __('widgets.rejected_orders_description'))
                ->descriptionIcon('heroicon-m-x-circle')
                ->color('danger'),

            Stat::make(__('widgets.under_processing_orders'), Number::format($underProcessingOrders))
                ->description($selectedYear ? __('widgets.under_processing_orders_in_year', ['year' => $selectedYear]) : __('widgets.under_processing_orders_description'))
                ->descriptionIcon('heroicon-m-clock')
                ->color('warning'),
        ];
    }

    public function getColumns(): int
    {
        return 4;
    }
}
