<?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 ClassificationOrdersStatsOverview extends BaseWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    public static ?int $sort = 2;

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

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

        // Build base query for classification orders
        $query = Order::where('status', Order::STATUS_CLASSIFICATION)->filterByTypePermissions();

        if ($selectedYear) {
            $query->whereYear('created_at', $selectedYear);
        }

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

        $classificationOrdersCount = (clone $query)->count();

        // Calculate total families from classification orders
        $totalFamilies = (clone $query)->sum('number_of_families');

        return [
            Stat::make(__('widgets.pending_classification_orders'), Number::format($classificationOrdersCount))
                ->description(__('widgets.pending_classification_orders_description'))
                ->descriptionIcon('heroicon-m-clipboard-document-list')
                ->color('warning'),

            Stat::make(__('widgets.number_of_families_pending_classification'), Number::format($totalFamilies))
                ->description(__('widgets.number_of_families_pending_classification_description'))
                ->descriptionIcon('heroicon-m-user-group')
                ->color('info'),
        ];
    }

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