import { Loader, Stack, Typography } from '@tidbcloud/uikit'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { Link } from 'react-router-dom'

import useStores from 'dbaas/stores/useStores'

/**
 * A lightweight access-denied view with built-in loading detection.
 *
 * While the permission-related queries (user roles & profile) are still
 * fetching, a "Validating Permissions" spinner is shown so the user never
 * sees a premature "Access Denied" flash. Once queries settle, a static
 * denied message is displayed with a link to the users page (pre-filled
 * with the current user's email).
 *
 * This replaces the previous dynamic version that attempted to display
 * the user's current role name, which was misleading when a user holds
 * multiple roles across different scopes (org, project, tidb).
 */
export const AccessDeniedView = observer(({ mode = 'denied' }: { mode?: 'denied' | 'loading' }) => {
  const {
    store: {
      userProfile: { email }
    }
  } = useStores()

  if (mode === 'loading') {
    return (
      <Stack align="center" justify="center" gap={8} mih={512} h="100%">
        <Loader size={32} />
        <Typography variant="headline-md" ta="center">
          Validating Permissions
        </Typography>
        <Typography variant="body-lg" ta="center">
          Please wait a moment.
        </Typography>
      </Stack>
    )
  }

  const usersPageLink = `/org-settings/users${email ? `?email=${encodeURIComponent(email)}` : ''}`

  return (
    <Stack align="center" justify="center" gap={8} mih={512} h="100%">
      <IconAlertCircle size={32} c="carbon.7" />
      <Typography variant="headline-md" ta="center">
        Access Denied
      </Typography>
      <Typography variant="body-lg" ta="center" maw={480}>
        You don't have permission to access this page.
        <br />
        Please <Link to={usersPageLink}>check your current role</Link> or contact your administrator for access.
      </Typography>
    </Stack>
  )
})
