import React from 'react'

import { Box, Center, Loader } from '@mantine/core'
import { Outlet, useParams } from 'react-router-dom'

import {
  useCurCluster,
  useCurOrg,
  useQueryCluster,
  useQueryOrg
} from '~/hooks/state'

import AppLayout from './AppLayout'
import ClusterNavBar from './ClusterNavBar'

// Make sure the pages inside the ClusterGuard have curOrg and curCluster value
// Match /orgs/:orgId/clusters/:cid routes
interface ClusterGuardProps {
  standalone?: boolean
}

const ClusterGuard: React.FC<ClusterGuardProps> = ({ standalone = false }) => {
  const { orgId, cid } = useParams<'orgId' | 'cid'>()

  useQueryOrg(orgId || '')
  const { curOrg } = useCurOrg()

  useQueryCluster(orgId || '', cid || '')
  const { curCluster } = useCurCluster()
  const contentLoading = !curOrg || !curCluster

  if (standalone) {
    return (
      <Box p={24} style={{ minHeight: '100vh' }}>
        {contentLoading ? (
          <Center style={{ height: 'calc(100vh - 48px)' }}>
            <Loader variant='bars' size='md' />
          </Center>
        ) : (
          <Outlet />
        )}
      </Box>
    )
  }

  return (
    <AppLayout contentLoading={contentLoading} navbar={<ClusterNavBar />}>
      <Outlet />
    </AppLayout>
  )
}

export default ClusterGuard
