<?php

namespace App\Filament\Widgets;

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

class ProjectCostOverview extends BaseWidget
{
    use HasWidgetShield;
    use InteractsWithPageFilters;

    protected static ?int $sort = 2;

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

    public function getHeading(): string
    {
        return __('pages.projects_dashboard').' - '.__('performance_dashboard.total_project_costs');
    }

    protected function getStats(): array
    {
        // Get filter values
        $selectedYear = $this->filters['year'] ?? null;
        $selectedDepartmentId = $this->filters['department_id'] ?? null;
        $selectedWalletId = $this->filters['performance_wallet_id'] ?? null;
        $selectedInitiativeId = $this->filters['initiative_id'] ?? null;

        // Build query with filters
        $query = ProjectCharter::query();

        // Apply year filter
        if ($selectedYear) {
            $query->where(function ($subQuery) use ($selectedYear) {
                $subQuery->whereYear('start_date', $selectedYear)
                    ->orWhereYear('expected_end_date', $selectedYear);
            });
        }

        if ($selectedInitiativeId) {
            $query->whereHas('initiativeProject', function ($q) use ($selectedInitiativeId) {
                $q->where('initiative_id', $selectedInitiativeId);
            });
        } elseif ($selectedWalletId) {
            $query->whereHas('initiativeProject.initiative', function ($q) use ($selectedWalletId) {
                $q->where('performance_wallet_id', $selectedWalletId);
            });
        } elseif ($selectedDepartmentId) {
            $query->whereHas('initiativeProject.initiative.performanceWallet.performanceCard', function ($q) use ($selectedDepartmentId) {
                $q->where('department_id', $selectedDepartmentId);
            });
        }

        $totalCost = $query->sum('total_cost') ?? 0;
        $averageCost = $query->where('total_cost', '>', 0)->avg('total_cost') ?? 0;

        return [
            Stat::make(__('performance_dashboard.total_project_costs'), new HtmlString('<span class="icon-saudi_riyal"></span>'.number_format($totalCost, 2)))
                ->description($this->getTotalCostDescription($selectedDepartmentId, $selectedWalletId, $selectedInitiativeId))
                ->descriptionIcon('heroicon-m-currency-dollar')
                ->color('success'),

            Stat::make(__('performance_dashboard.average_project_cost'), new HtmlString('<span class="icon-saudi_riyal"></span>'.number_format($averageCost, 2)))
                ->description($this->getAverageCostDescription($selectedDepartmentId, $selectedWalletId, $selectedInitiativeId))
                ->descriptionIcon('heroicon-m-calculator')
                ->color('info'),
        ];
    }

    private function getTotalCostDescription(?int $selectedDepartmentId, ?int $selectedWalletId, ?int $selectedInitiativeId): string
    {
        if ($selectedInitiativeId) {
            return __('performance_dashboard.total_project_costs_in_initiative');
        } elseif ($selectedWalletId) {
            return __('performance_dashboard.total_project_costs_in_wallet');
        } else {
            return __('performance_dashboard.total_project_costs_description');
        }
    }

    private function getAverageCostDescription(?int $selectedDepartmentId, ?int $selectedWalletId, ?int $selectedInitiativeId): string
    {
        if ($selectedInitiativeId) {
            return __('performance_dashboard.average_project_cost_in_initiative');
        } elseif ($selectedWalletId) {
            return __('performance_dashboard.average_project_cost_in_wallet');
        } else {
            return __('performance_dashboard.average_project_cost_description');
        }
    }

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