<?php

namespace App\Filament\Tenant\Pages;

use App\Models\Tenant\User;
use App\Models\Tenant\WorkOrderWork;
use Carbon\Carbon;
use Filament\Pages\Page;

/**
 * Aggregate KPI dashboard per mechanic over a period: tasks done, norm vs
 * actual hours, efficiency %, revenue from manopere. Period defaults to
 * current month.
 */
class MechanicKpi extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-chart-bar';

    protected static ?string $navigationLabel = 'KPI mecanici';

    protected static string|\UnitEnum|null $navigationGroup = 'Service';

    protected static ?int $navigationSort = 28;

    protected static ?string $title = 'KPI mecanici';

    protected string $view = 'filament.tenant.pages.mechanic-kpi';

    public string $period = '';

    public function mount(): void
    {
        $this->period = now()->format('Y-m');
    }

    public function shiftMonth(int $delta): void
    {
        $this->period = Carbon::parse($this->period . '-01')->addMonths($delta)->format('Y-m');
    }

    public function getRows(): array
    {
        [$y, $m] = explode('-', $this->period);

        $rows = WorkOrderWork::query()
            ->with('workOrder:id,master_id')
            ->where('mechanic_status', 'done')
            ->whereYear('mechanic_done_at', $y)
            ->whereMonth('mechanic_done_at', $m)
            ->get()
            ->groupBy(fn ($w) => $w->workOrder?->master_id ?: 0);

        $masters = User::whereIn('id', $rows->keys()->all())->get(['id', 'name'])->keyBy('id');

        $out = [];
        foreach ($rows as $masterId => $works) {
            if (! $masterId) continue;
            $totalNorm = (float) $works->sum('hours');
            $totalActual = (float) $works->sum('actual_hours');
            $efficiencyPct = $totalNorm > 0 ? round(100 * $totalActual / $totalNorm) : null;
            $cls = match (true) {
                $efficiencyPct === null => 'gray',
                $efficiencyPct <= 100 => 'green',
                $efficiencyPct <= 130 => 'amber',
                default => 'red',
            };
            $out[] = [
                'master_id' => $masterId,
                'master_name' => $masters[$masterId]?->name ?? 'Mecanic #' . $masterId,
                'tasks_done' => $works->count(),
                'norm_hours' => round($totalNorm, 2),
                'actual_hours' => round($totalActual, 2),
                'efficiency_pct' => $efficiencyPct,
                'efficiency_class' => $cls,
                'revenue' => round((float) $works->sum('total'), 2),
            ];
        }

        usort($out, fn ($a, $b) => $b['revenue'] <=> $a['revenue']);
        return $out;
    }

    public function getPeriodLabel(): string
    {
        return Carbon::parse($this->period . '-01')->locale('ro')->isoFormat('MMMM YYYY');
    }
}
