import { useNavigate } from '@/router'
import { Alert } from '@blueprintjs/core'
import { useAuthIdentity } from '@inject/graphql/auth'
import schema from '@inject/graphql/schema.remote.json'
import Keys from '@inject/shared/localstorage/keys'
import { useLocalStorageState } from 'ahooks'
import 'graphql-voyager/dist/voyager.css'
import { Suspense, lazy } from 'react'

const Voyager = lazy(() =>
  import('graphql-voyager').then(module => ({ default: module.Voyager }))
)

const GraphiQLPage = /* @__PURE__ */ () => {
  const { isStaff } = useAuthIdentity()
  const [confirmed, setConfirmed] = useLocalStorageState(
    Keys.VOYAGER_CONFIRMED,
    {
      defaultValue: false,
    }
  )
  const nav = useNavigate()

  if (!isStaff) {
    return <p>You are not authorized to access this page</p>
  }

  return (
    <>
      <Suspense fallback={<p>Loading...</p>}>
        {/* @ts-ignore */}
        <Voyager
          introspection={{
            // @ts-ignore
            data: schema,
          }}
        />
      </Suspense>
      <Alert
        isOpen={!confirmed}
        cancelButtonText='Cancel'
        onCancel={() => nav('/')}
        confirmButtonText='Confirm'
        icon='warning-sign'
        intent='warning'
        onConfirm={() => setConfirmed(true)}
      >
        <p>You are about to inspect GraphQL API. Please confirm entry</p>
        <p>
          <strong>
            Do not use this interface unless you know what you are doing.
          </strong>
        </p>
      </Alert>
    </>
  )
}

export default GraphiQLPage
