import { Alert, Box, Card, Group, Stack, Typography } from '@tidbcloud/uikit'
import { FormPasswordInput, FormTextInput } from '@tidbcloud/uikit/biz'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { useQuery } from 'react-query'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useOrgProjectClusterIds } from 'dbaas/features/Common'
import { CloudProviderConst } from 'dbaas/features/Project'
import { migrationServiceGetVpcInfo } from 'dbaas/services/api-clients/legacy/serverless'

export const FormTargetConnection = ({
  isPrivate,
  region,
  id,
  name,
  cluster
}: {
  isPrivate?: boolean
  region?: string
  id?: string
  name?: string
  cluster?: SharedCluster | null
}) => {
  const { orgId, projectId, clusterId } = useOrgProjectClusterIds()
  const { data, isLoading } = useQuery({
    queryKey: ['migrationServiceGetVpcInfo', orgId, projectId, clusterId],
    queryFn: () => migrationServiceGetVpcInfo(orgId, projectId, clusterId!, {}),
    enabled: !!cluster?.computed.isEssential && isPrivate && !!orgId && !!projectId && !!clusterId,
    refetchOnWindowFocus: false
  })
  const showPrivateLinkInfo = isPrivate && !!cluster?.computed.isEssential
  const provider = cluster?.provider
  const cloudAccountText = isLoading ? 'loading...' : (data?.account_id ?? 'unavailable')
  const accountLabel = (() => {
    switch (provider) {
      default:
        return 'TiDB Cloud account ID'
    }
  })()
  const availabilityZonesText = isLoading
    ? 'loading...'
    : data?.availability_zones?.length
      ? data.availability_zones.join(', ')
      : 'unavailable'
  const availabilityInstruction =
    provider === CloudProviderConst.ALICLOUD
      ? 'Ensure the Private Link endpoint you create uses availability zones that exactly match TiDB Cloud'
      : 'Ensure the Private Link endpoint you create uses at least one availability zone that overlaps with TiDB Cloud'

  return (
    <Stack m={24}>
      <Typography variant="headline-sm">Target Connection Profile</Typography>

      <Group align="stretch">
        {region && id && name && (
          <Card
            withBorder={false}
            bg="carbon.2"
            sx={() => ({
              flex: 1,
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'space-evenly'
            })}
          >
            <Group justify="space-between">
              <span>Region</span>
              <b>{region}</b>
            </Group>
            <Group justify="space-between">
              <span>Cluster ID</span>
              <b>{id}</b>
            </Group>
            <Group justify="space-between">
              <span>Cluster Name</span>
              <b>{name}</b>
            </Group>
          </Card>
        )}

        <Stack sx={{ flex: 1 }}>
          <FormTextInput
            name="cluster_username"
            label="User Name"
            placeholder="Enter the TiDB cluster username"
            inputWrapperOrder={['label', 'input', 'description', 'error']}
            description={
              <span>
                Please refer to the{' '}
                <a
                  tabIndex={-1}
                  href="https://docs.pingcap.com/tidbcloud/migrate-from-mysql-using-data-migration#grant-required-privileges-to-the-downstream-tidb-cloud-cluster"
                  target="_blank"
                  rel="noreferrer"
                >
                  documentation
                </a>{' '}
                for the required privileges
              </span>
            }
          />

          <FormPasswordInput name="cluster_password" label="Password" placeholder="Enter the TiDB cluster password" />
        </Stack>
      </Group>

      {showPrivateLinkInfo && (
        <Alert color="peacock" icon={<IconAlertCircle />}>
          <Box component="ul" m={0} pl={16}>
            <li>
              Authorize the {accountLabel} <b>{cloudAccountText}</b> to create an endpoint for your Private Link service
              before testing the connection.
            </li>
            <li>
              {availabilityInstruction}: <b>{availabilityZonesText}</b>.
            </li>
          </Box>
        </Alert>
      )}
    </Stack>
  )
}
