import { Alert, Box, Button, HoverCard, Stack } from '@tidbcloud/uikit'
import { useDisclosure } from '@tidbcloud/uikit/hooks'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { PageShell } from 'dbaas/layouts/v5/page'
import { ServerlessConnectionV2 } from 'dbaas/screens/ClusterV2/features/Connection/serverless'

import { EssentialPrivateLink } from './EssentialPrivateLink'
import { PrivateEndpointConfig } from './PrivateEndpoint'
import { PublicEndpointConfig } from './PublicEndpoint'

export const ServerlessNetworkPage = ({ cluster }: { cluster: SharedCluster }) => {
  const disabled = cluster?.computed?.creating || cluster?.computed?.recovering
  const [connectOpened, connectHandlers] = useDisclosure()

  return (
    <PageShell
      title="Networking"
      headerProps={{
        rightSection: (
          <HoverCard shadow="md" position="left" withArrow disabled={!disabled}>
            <HoverCard.Target>
              <Box component="span">
                <Button
                  disabled={disabled}
                  onClick={connectHandlers.open}
                  size="sm"
                  data-mp-event="Connect Button Clicked"
                  data-mp-source="Networking"
                  data-mp-service-plan={cluster?.servicePlan}
                  data-testid="serverless-networking-connect"
                >
                  Connect
                </Button>
              </Box>
            </HoverCard.Target>
            <HoverCard.Dropdown>Retry after the instance is available.</HoverCard.Dropdown>
          </HoverCard>
        )
      }}
      bodyProps={{
        pt: 0
      }}
    >
      <ServerlessConnectionV2
        cluster={cluster}
        branchScope="all"
        opened={connectOpened}
        onClose={connectHandlers.close}
      />
      <Stack gap="xl">
        <Alert>
          Your instance supports two ways to configure connectivity to your servers: Public Endpoint and Private
          Endpoint. Public Endpoint can be disabled if needed. Learn more about{' '}
          <a
            href="https://docs.pingcap.com/tidbcloud/connect-to-tidb-cluster-serverless#network"
            target="_blank"
            rel="noreferrer"
          >
            connection types
          </a>
          .
        </Alert>

        <PublicEndpointConfig clusterId={cluster.id} />
        <PrivateEndpointConfig cluster={cluster} />

        {cluster.computed.isEssential && <EssentialPrivateLink cluster={cluster} />}
      </Stack>
    </PageShell>
  )
}
