"use client"

import { useRouter } from "next/navigation"
import { useEffect } from "react"
import { ScopeGuard } from "@/components/auth/scope-guard"
import { CenteredSpinner } from "@/components/loading/spinner"
import { AlertNotification } from "@/components/notifications"
import { WorkspaceRbacRoles } from "@/components/workspaces/workspace-rbac-roles"
import { useEntitlements } from "@/hooks/use-entitlements"
import { useWorkspaceDetails } from "@/hooks/use-workspace"
import { useWorkspaceId } from "@/providers/workspace-id"

export default function WorkspaceRolesPage() {
  const router = useRouter()
  const workspaceId = useWorkspaceId()
  const { workspace, workspaceLoading, workspaceError } = useWorkspaceDetails()
  const { hasEntitlement, isLoading: entitlementsLoading } = useEntitlements()
  const rbacEnabled = hasEntitlement("rbac_addons")

  useEffect(() => {
    if (!entitlementsLoading && !rbacEnabled) {
      router.replace(`/workspaces/${workspaceId}/members`)
    }
  }, [entitlementsLoading, rbacEnabled, router, workspaceId])

  if (entitlementsLoading || !rbacEnabled) {
    return <CenteredSpinner />
  }
  if (workspaceLoading) {
    return <CenteredSpinner />
  }
  if (workspaceError) {
    return (
      <AlertNotification
        level="error"
        message="Error loading workspace info."
      />
    )
  }
  if (!workspace) {
    return <AlertNotification level="error" message="Workspace not found." />
  }
  return (
    <ScopeGuard scope="org:rbac:read" fallback={null} loading={null}>
      <div className="size-full overflow-auto">
        <div className="container flex h-full flex-col space-y-12 py-8">
          <WorkspaceRbacRoles workspaceId={workspace.id} hideCreateButton />
        </div>
      </div>
    </ScopeGuard>
  )
}
