<?php

namespace App\Filament\Resources\ManagedEnvironmentResource\Pages;

use App\Filament\Resources\ManagedEnvironmentResource;
use App\Filament\Widgets\ManagedEnvironment\AdminRolesSummaryWidget;
use App\Filament\Widgets\ManagedEnvironment\RecentOperationsSummary;
use App\Filament\Widgets\ManagedEnvironment\ManagedEnvironmentArchivedBanner;
use App\Filament\Widgets\ManagedEnvironment\ManagedEnvironmentVerificationReport;
use App\Jobs\RefreshTenantRbacHealthJob;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\OperationRunService;
use App\Support\Auth\Capabilities;
use App\Support\OperationRunLinks;
use App\Support\OperationRunType;
use App\Support\OpsUx\OperationUxPresenter;
use App\Support\OpsUx\OpsUxBrowserEvents;
use App\Support\Rbac\UiEnforcement;
use App\Support\Tenants\TenantActionSurface;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;

class ViewManagedEnvironment extends ViewRecord
{
    protected static string $resource = ManagedEnvironmentResource::class;

    public static function verificationHeaderActionLabel(): string
    {
        return 'Verify configuration';
    }

    public static function verificationHeaderActionHint(): string
    {
        return 'Use "'.self::verificationHeaderActionLabel().'" in the tenant header to run verification again after you inspect the current operation.';
    }

    public function getHeaderWidgetsColumns(): int|array
    {
        return 1;
    }

    protected function getHeaderWidgets(): array
    {
        return [
            ManagedEnvironmentArchivedBanner::class,
            RecentOperationsSummary::class,
            ManagedEnvironmentVerificationReport::class,
            AdminRolesSummaryWidget::class,
        ];
    }

    protected function getHeaderActions(): array
    {
        return array_values(array_filter([
            ManagedEnvironmentResource::makeMembershipsAction(),
            Actions\ActionGroup::make([
                ManagedEnvironmentResource::makeAdminConsentAction(),
                ManagedEnvironmentResource::makeOpenInEntraAction(),
            ])
                ->label('External links')
                ->icon('heroicon-o-arrow-top-right-on-square')
                ->color('gray')
                ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
                    && ManagedEnvironmentResource::tenantViewExternalGroupVisible($this->getRecord())),
            Actions\ActionGroup::make([
                ManagedEnvironmentResource::makeSyncTenantAction(),
                ManagedEnvironmentResource::makeVerifyConfigurationAction('tenant_view_header'),
                ManagedEnvironmentResource::rbacAction(),
                UiEnforcement::forAction(
                    Actions\Action::make('refresh_rbac')
                        ->label('Refresh RBAC status')
                        ->icon('heroicon-o-arrow-path')
                        ->color('primary')
                        ->requiresConfirmation()
                        ->visible(fn (ManagedEnvironment $record): bool => ManagedEnvironmentResource::tenantSetupMutationVisible($record))
                        ->action(function (ManagedEnvironment $record): void {
                            $user = auth()->user();

                            if (! $user instanceof User) {
                                abort(403);
                            }

                            if (! $user->canAccessTenant($record)) {
                                abort(404);
                            }

                            /** @var OperationRunService $runs */
                            $runs = app(OperationRunService::class);

                            $opRun = $runs->ensureRun(
                                tenant: $record,
                                type: OperationRunType::RbacHealthCheck->value,
                                inputs: [
                                    'managed_environment_id' => (int) $record->getKey(),
                                    'surface' => 'tenant_view_header',
                                ],
                                initiator: $user,
                            );

                            $runUrl = OperationRunLinks::tenantlessView($opRun);

                            if ($opRun->wasRecentlyCreated === false) {
                                OpsUxBrowserEvents::dispatchRunEnqueued($this);

                                OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
                                    ->actions([
                                        Actions\Action::make('view_run')
                                            ->label(OperationRunLinks::openLabel())
                                            ->url($runUrl),
                                    ])
                                    ->send();

                                return;
                            }

                            RefreshTenantRbacHealthJob::dispatch(
                                (int) $record->getKey(),
                                (int) $user->getKey(),
                                $opRun,
                            );

                            OpsUxBrowserEvents::dispatchRunEnqueued($this);

                            OperationUxPresenter::queuedToast((string) $opRun->type)
                                ->actions([
                                    Actions\Action::make('view_run')
                                        ->label(OperationRunLinks::openLabel())
                                        ->url($runUrl),
                                ])
                                ->send();
                        }),
                )
                    ->preserveVisibility()
                    ->requireCapability(Capabilities::PROVIDER_RUN)
                    ->apply(),
            ])
                ->label('Setup')
                ->icon('heroicon-o-wrench-screwdriver')
                ->color('gray')
                ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
                    && ManagedEnvironmentResource::tenantViewSetupGroupVisible($this->getRecord())),
            Actions\ActionGroup::make([
                ManagedEnvironmentResource::makeTenantViewMarkReviewedAction(),
                ManagedEnvironmentResource::makeTenantViewMarkFollowUpNeededAction(),
            ])
                ->label('Triage')
                ->icon('heroicon-o-check-circle')
                ->color('gray')
                ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
                    && ManagedEnvironmentResource::tenantViewTriageGroupVisible($this->getRecord())),
            Actions\ActionGroup::make([
                ManagedEnvironmentResource::makeRestoreTenantAction(TenantActionSurface::TenantViewHeader),
                ManagedEnvironmentResource::makeRestoreTenantToWorkspaceAction(),
                ManagedEnvironmentResource::makeRemoveTenantFromWorkspaceAction(),
                ManagedEnvironmentResource::makeArchiveTenantAction(TenantActionSurface::TenantViewHeader),
            ])
                ->label('Lifecycle')
                ->icon('heroicon-o-archive-box')
                ->color('gray')
                ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
                    && ManagedEnvironmentResource::tenantViewLifecycleGroupVisible($this->getRecord())),
        ]));
    }
}
