import { Alert, Box, Card, Stack, Typography } from '@tidbcloud/uikit'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'

import { CodeWithAction } from 'dbaas/screens/OrgSettings/features/APIKeys/components/CodeWithAction'
import { PropertyItem } from 'dbaas/screens/OrgSettings/features/APIKeys/components/PropertyItem'
import { useCreateApiKeyForMsp } from 'dbaas/services/account'
import { getErrorMessage } from 'dbaas/services/errorCodes'

export const MSPAPIKeys = observer(() => {
  const params = new URLSearchParams(window.location.search)
  const token = params.get('token') || ''
  const { data, error } = useCreateApiKeyForMsp(
    { token },
    {
      query: {
        refetchOnWindowFocus: false,
        refetchInterval: false,
        retry: false
      }
    }
  )

  return (
    <Box h="100vh" pt={36}>
      <Card sx={() => ({ width: 800, margin: '0 auto' })} p={24}>
        <Stack>
          <Typography variant="title-lg">Initial Key for MSP Management API</Typography>
          <PropertyItem label="Public Key" align="center">
            <CodeWithAction>{data?.access_key || ''}</CodeWithAction>
          </PropertyItem>
          <PropertyItem label="Private Key" align="center">
            <CodeWithAction>{data?.secret_key || ''}</CodeWithAction>
          </PropertyItem>
          {!!data?.access_key && !error && (
            <Alert icon={<IconAlertCircle size={14} color="inherit" />}>
              Copy your private key and store it in a secure location. After you leave this page, the full private key
              is unavailable.
            </Alert>
          )}
          {!!error && (
            <Alert color="red" icon={<IconAlertCircle size={14} color="inherit" />}>
              {getErrorMessage(error)}
            </Alert>
          )}
        </Stack>
      </Card>
    </Box>
  )
})

export default MSPAPIKeys
