<?php

declare(strict_types=1);

namespace App\Filament\Concerns;

use App\Support\Navigation\WorkspaceHubFilterStateResetter;
use App\Support\Navigation\WorkspaceHubRegistry;
use Illuminate\Http\Request;

trait ClearsWorkspaceHubEnvironmentFilterState
{
    protected function resetWorkspaceHubEnvironmentFilterStateForCleanEntry(?Request $request = null): void
    {
        $resetter = $this->workspaceHubFilterStateResetter();
        $resetter->neutralizeEnvironmentLikeQueryState($request);

        if (
            ! $resetter->shouldResetForCleanWorkspaceHubEntry($request)
            && WorkspaceHubRegistry::requestHasEnvironmentFilterQuery($request)
        ) {
            return;
        }

        $this->clearWorkspaceHubEnvironmentFilterState($request);
    }

    protected function clearWorkspaceHubEnvironmentFilterState(?Request $request = null): void
    {
        $this->forgetWorkspaceHubEnvironmentFilterSessionState($request);
        $this->clearWorkspaceHubEnvironmentTableFilterState();
    }

    protected function cleanWorkspaceHubUrl(string $url): string
    {
        return $this->workspaceHubFilterStateResetter()->cleanUrl($url);
    }

    protected function redirectToCleanWorkspaceHubUrl(string $url, ?Request $request = null): void
    {
        $this->clearWorkspaceHubEnvironmentFilterState($request);
        $this->redirect($this->cleanWorkspaceHubUrl($url), navigate: true);
    }

    private function forgetWorkspaceHubEnvironmentFilterSessionState(?Request $request = null): void
    {
        if (! method_exists($this, 'getTableFiltersSessionKey')) {
            return;
        }

        $this->workspaceHubFilterStateResetter()
            ->forgetPersistedEnvironmentLikeFilters($this->getTableFiltersSessionKey(), $request);
    }

    private function clearWorkspaceHubEnvironmentTableFilterState(): void
    {
        $resetter = $this->workspaceHubFilterStateResetter();

        $tableFilters = $this->tableFilters ?? null;

        if (is_array($tableFilters)) {
            $this->tableFilters = $resetter->clearLivewireTableFilterState($tableFilters);
        }

        $tableDeferredFilters = $this->tableDeferredFilters ?? null;

        if (is_array($tableDeferredFilters)) {
            $this->tableDeferredFilters = $resetter->clearLivewireTableFilterState($tableDeferredFilters);
        }
    }

    private function workspaceHubFilterStateResetter(): WorkspaceHubFilterStateResetter
    {
        return app(WorkspaceHubFilterStateResetter::class);
    }
}
