<?php

declare(strict_types=1);

namespace App\Filament\Pages;

use App\Filament\Resources\ProviderConnectionResource;
use App\Filament\Resources\TenantResource;
use App\Models\Tenant;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Services\Intune\TenantRequiredPermissionsViewModelBuilder;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Pages\Page;

class TenantRequiredPermissions extends Page
{
    protected static bool $isDiscovered = false;

    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $slug = 'tenants/{tenant}/required-permissions';

    protected static ?string $title = 'Required permissions';

    protected string $view = 'filament.pages.tenant-required-permissions';

    public string $status = 'missing';

    public string $type = 'all';

    /**
     * @var array<int, string>
     */
    public array $features = [];

    public string $search = '';

    /**
     * @var array<string, mixed>
     */
    public array $viewModel = [];

    public ?Tenant $scopedTenant = null;

    public static function canAccess(): bool
    {
        return static::hasScopedTenantAccess(static::resolveScopedTenant());
    }

    public function currentTenant(): ?Tenant
    {
        return $this->scopedTenant;
    }

    public function mount(): void
    {
        $tenant = static::resolveScopedTenant();

        if (! $tenant instanceof Tenant || ! static::hasScopedTenantAccess($tenant)) {
            abort(404);
        }

        $this->scopedTenant = $tenant;

        $queryFeatures = request()->query('features', $this->features);

        $state = TenantRequiredPermissionsViewModelBuilder::normalizeFilterState([
            'status' => request()->query('status', $this->status),
            'type' => request()->query('type', $this->type),
            'features' => is_array($queryFeatures) ? $queryFeatures : [],
            'search' => request()->query('search', $this->search),
        ]);

        $this->status = $state['status'];
        $this->type = $state['type'];
        $this->features = $state['features'];
        $this->search = $state['search'];

        $this->refreshViewModel();
    }

    public function updatedStatus(): void
    {
        $this->refreshViewModel();
    }

    public function updatedType(): void
    {
        $this->refreshViewModel();
    }

    public function updatedFeatures(): void
    {
        $this->refreshViewModel();
    }

    public function updatedSearch(): void
    {
        $this->refreshViewModel();
    }

    public function applyFeatureFilter(string $feature): void
    {
        $feature = trim($feature);

        if ($feature === '') {
            return;
        }

        if (in_array($feature, $this->features, true)) {
            $this->features = array_values(array_filter(
                $this->features,
                static fn (string $value): bool => $value !== $feature,
            ));
        } else {
            $this->features[] = $feature;
        }

        $this->features = array_values(array_unique($this->features));

        $this->refreshViewModel();
    }

    public function clearFeatureFilter(): void
    {
        $this->features = [];

        $this->refreshViewModel();
    }

    public function resetFilters(): void
    {
        $this->status = 'missing';
        $this->type = 'all';
        $this->features = [];
        $this->search = '';

        $this->refreshViewModel();
    }

    private function refreshViewModel(): void
    {
        $tenant = $this->scopedTenant;

        if (! $tenant instanceof Tenant) {
            $this->viewModel = [];

            return;
        }

        $builder = app(TenantRequiredPermissionsViewModelBuilder::class);

        $this->viewModel = $builder->build($tenant, [
            'status' => $this->status,
            'type' => $this->type,
            'features' => $this->features,
            'search' => $this->search,
        ]);

        $filters = $this->viewModel['filters'] ?? null;

        if (is_array($filters)) {
            $this->status = (string) ($filters['status'] ?? $this->status);
            $this->type = (string) ($filters['type'] ?? $this->type);
            $this->features = is_array($filters['features'] ?? null) ? $filters['features'] : $this->features;
            $this->search = (string) ($filters['search'] ?? $this->search);
        }
    }

    public function reRunVerificationUrl(): string
    {
        $tenant = $this->scopedTenant;

        if ($tenant instanceof Tenant) {
            return TenantResource::getUrl('view', ['record' => $tenant]);
        }

        return route('admin.onboarding');
    }

    public function manageProviderConnectionUrl(): ?string
    {
        $tenant = $this->scopedTenant;

        if (! $tenant instanceof Tenant) {
            return null;
        }

        return ProviderConnectionResource::getUrl('index', ['tenant' => $tenant], panel: 'admin');
    }

    protected static function resolveScopedTenant(): ?Tenant
    {
        $routeTenant = request()->route('tenant');

        if ($routeTenant instanceof Tenant) {
            return $routeTenant;
        }

        if (is_string($routeTenant) && $routeTenant !== '') {
            return Tenant::query()
                ->where('external_id', $routeTenant)
                ->first();
        }

        return null;
    }

    private static function hasScopedTenantAccess(?Tenant $tenant): bool
    {
        $user = auth()->user();

        if (! $tenant instanceof Tenant || ! $user instanceof User) {
            return false;
        }

        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());

        if ($workspaceId === null || (int) $tenant->workspace_id !== (int) $workspaceId) {
            return false;
        }

        $isWorkspaceMember = WorkspaceMembership::query()
            ->where('workspace_id', (int) $workspaceId)
            ->where('user_id', (int) $user->getKey())
            ->exists();

        if (! $isWorkspaceMember) {
            return false;
        }

        return $user->canAccessTenant($tenant);
    }
}
