<?php

namespace App\Livewire;

use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Support\OpsUx\ActiveRuns;
use App\Support\OpsUx\OpsUxBrowserEvents;
use Filament\Facades\Filament;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\On;
use Livewire\Component;

class BulkOperationProgress extends Component
{
    private const VISIBLE_RUN_LIMIT = 3;

    /**
     * @var Collection<int, OperationRun>
     */
    public Collection $runs;

    public int $overflowCount = 0;

    public bool $disabled = false;

    public bool $hasActiveRuns = false;

    public bool $hasVisibleRuns = false;

    public int $activeRunCount = 0;

    public ?int $tenantId = null;

    public function mount(): void
    {
        $this->runs = collect();

        $tenant = Filament::getTenant();
        $this->tenantId = $tenant instanceof ManagedEnvironment ? (int) $tenant->id : null;

        $this->refreshRuns();
    }

    #[On(OpsUxBrowserEvents::RunEnqueued)]
    public function onRunEnqueued(?int $tenantId = null): void
    {
        if ($tenantId !== null) {
            $this->tenantId = $tenantId;
        }

        $this->refreshRuns();
    }

    #[Computed]
    public function activeRuns(): Collection
    {
        return $this->runs;
    }

    public function refreshRuns(): void
    {
        $tenantId = $this->tenantId;

        // Best-effort: if we're mounted on a tenant page, capture it once.
        if ($tenantId === null) {
            $tenant = Filament::getTenant();
            $tenantId = $tenant instanceof ManagedEnvironment ? (int) $tenant->id : null;
            $this->tenantId = $tenantId;
        }

        if ($tenantId === null) {
            $this->disabled = true;
            $this->runs = collect();
            $this->overflowCount = 0;
            $this->hasActiveRuns = false;

            return;
        }

        if (! auth()->user()?->can('viewAny', OperationRun::class)) {
            $this->disabled = true;
            $this->runs = collect();
            $this->overflowCount = 0;
            $this->hasActiveRuns = false;

            return;
        }

        $this->disabled = false;

        $activeCount = ActiveRuns::countForTenantId($tenantId);
        $visibleCount = ActiveRuns::shellVisibleCountForTenantId($tenantId);

        $this->activeRunCount = $activeCount;
        $this->runs = ActiveRuns::shellVisibleForTenantId($tenantId, self::VISIBLE_RUN_LIMIT);
        $this->overflowCount = max(0, $visibleCount - self::VISIBLE_RUN_LIMIT);
        $this->hasActiveRuns = $activeCount > 0;
        $this->hasVisibleRuns = $visibleCount > 0;
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.bulk-operation-progress', [
            'tenant' => Filament::getTenant(),
        ]);
    }
}
