<?php

namespace App\Providers\Filament;

use App\Filament\Pages\Auth\Login;
use App\Filament\Pages\ChooseTenant;
use App\Filament\Pages\ChooseWorkspace;
use App\Filament\Pages\InventoryCoverage;
use App\Filament\Pages\NoAccess;
use App\Filament\Pages\Settings\WorkspaceSettings;
use App\Filament\Pages\TenantRequiredPermissions;
use App\Filament\Pages\WorkspaceOverview;
use App\Filament\Resources\AlertDeliveryResource;
use App\Filament\Resources\AlertDestinationResource;
use App\Filament\Resources\AlertRuleResource;
use App\Filament\Resources\BaselineProfileResource;
use App\Filament\Resources\BaselineSnapshotResource;
use App\Filament\Resources\InventoryItemResource;
use App\Filament\Resources\PolicyResource;
use App\Filament\Resources\ProviderConnectionResource;
use App\Filament\Resources\TenantResource;
use App\Filament\Resources\Workspaces\WorkspaceResource;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Services\Auth\WorkspaceRoleCapabilityMap;
use App\Support\Auth\Capabilities;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Navigation\NavigationItem;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\View\PanelsRenderHook;
use Filament\Widgets\AccountWidget;
use Filament\Widgets\FilamentInfoWidget;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;

class AdminPanelProvider extends PanelProvider
{
    public function panel(Panel $panel): Panel
    {
        $panel = $panel
            ->default()
            ->id('admin')
            ->path('admin')
            ->login(Login::class)
            ->brandName('TenantPilot')
            ->brandLogo(fn () => view('filament.admin.logo'))
            ->brandLogoHeight('2rem')
            ->homeUrl(fn (): string => route('admin.home'))
            ->favicon(asset('favicon.ico'))
            ->authenticatedRoutes(function (Panel $panel): void {
                ChooseWorkspace::registerRoutes($panel);
                ChooseTenant::registerRoutes($panel);
                NoAccess::registerRoutes($panel);
            })
            ->colors([
                'primary' => Color::Indigo,
            ])
            ->navigationItems([
                WorkspaceOverview::navigationItem(),
                NavigationItem::make('Integrations')
                    ->url(fn (): string => route('filament.admin.resources.provider-connections.index'))
                    ->icon('heroicon-o-link')
                    ->group('Settings')
                    ->sort(15)
                    ->visible(fn (): bool => ProviderConnectionResource::canViewAny()),
                NavigationItem::make('Settings')
                    ->url(fn (): string => WorkspaceSettings::getUrl(panel: 'admin'))
                    ->icon('heroicon-o-cog-6-tooth')
                    ->group('Settings')
                    ->sort(20)
                    ->visible(function (): bool {
                        $user = auth()->user();

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

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

                        if (! is_int($workspaceId)) {
                            return false;
                        }

                        $workspace = Workspace::query()->whereKey($workspaceId)->first();

                        if (! $workspace instanceof Workspace) {
                            return false;
                        }

                        /** @var WorkspaceCapabilityResolver $resolver */
                        $resolver = app(WorkspaceCapabilityResolver::class);

                        return $resolver->isMember($user, $workspace)
                            && $resolver->can($user, $workspace, Capabilities::WORKSPACE_SETTINGS_VIEW);
                    }),
                NavigationItem::make('Manage workspaces')
                    ->url(function (): string {
                        return route('filament.admin.resources.workspaces.index');
                    })
                    ->icon('heroicon-o-squares-2x2')
                    ->group('Settings')
                    ->sort(10)
                    ->visible(function (): bool {
                        $user = auth()->user();

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

                        $roles = WorkspaceRoleCapabilityMap::rolesWithCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);

                        return WorkspaceMembership::query()
                            ->where('user_id', (int) $user->getKey())
                            ->whereIn('role', $roles)
                            ->exists();
                    }),
                NavigationItem::make('Operations')
                    ->url(fn (): string => route('admin.operations.index'))
                    ->icon('heroicon-o-queue-list')
                    ->group('Monitoring')
                    ->sort(10),
                NavigationItem::make('Audit Log')
                    ->url(fn (): string => route('admin.monitoring.audit-log'))
                    ->icon('heroicon-o-clipboard-document-list')
                    ->group('Monitoring')
                    ->sort(30),
            ])
            ->renderHook(
                PanelsRenderHook::HEAD_END,
                fn () => view('filament.partials.livewire-intercept-shim')->render()
            )
            ->renderHook(
                PanelsRenderHook::TOPBAR_START,
                fn () => view('filament.partials.context-bar')->render()
            )
            ->renderHook(
                PanelsRenderHook::BODY_END,
                fn (): string => request()->routeIs('admin.workspace.managed-tenants.index', 'admin.onboarding', 'filament.admin.pages.choose-tenant')
                    ? ''
                    : ((bool) config('tenantpilot.bulk_operations.progress_widget_enabled', true)
                        ? view('livewire.bulk-operation-progress-wrapper')->render()
                        : '')
            )
            ->resources([
                TenantResource::class,
                PolicyResource::class,
                ProviderConnectionResource::class,
                InventoryItemResource::class,
                AlertDestinationResource::class,
                AlertRuleResource::class,
                AlertDeliveryResource::class,
                WorkspaceResource::class,
                BaselineProfileResource::class,
                BaselineSnapshotResource::class,
            ])
            ->discoverClusters(in: app_path('Filament/Clusters'), for: 'App\\Filament\\Clusters')
            ->discoverResources(in: app_path('Filament/Resources'), for: 'App\\Filament\\Resources')
            ->pages([
                InventoryCoverage::class,
                TenantRequiredPermissions::class,
                WorkspaceSettings::class,
            ])
            ->widgets([
                AccountWidget::class,
                FilamentInfoWidget::class,
            ])
            ->databaseNotifications()
            ->unsavedChangesAlerts()
            ->middleware([
                EncryptCookies::class,
                AddQueuedCookiesToResponse::class,
                StartSession::class,
                AuthenticateSession::class,
                ShareErrorsFromSession::class,
                VerifyCsrfToken::class,
                SubstituteBindings::class,
                'ensure-correct-guard:web',
                'ensure-workspace-selected',
                'ensure-filament-tenant-selected',
                DisableBladeIconComponents::class,
                DispatchServingFilamentEvent::class,
            ])
            ->authMiddleware([
                Authenticate::class,
            ]);

        if (! app()->runningUnitTests()) {
            $panel->viteTheme('resources/css/filament/admin/theme.css');
        }

        return $panel;
    }
}
