import useUrlState from '@ahooksjs/use-url-state'
import { Alert, Box, Button, Group, SegmentedControl, Stack } from '@tidbcloud/uikit'
import { useDisclosure } from '@tidbcloud/uikit/hooks'
import { observer } from 'mobx-react'
import { Link } from 'react-router-dom'

import { AccessDeniedHoverHint, AccessGuard } from 'dbaas/contexts/access-control'
import { CloudProviderConst, CloudProviderLabelConst } from 'dbaas/features/Project'
import { OrgPlanStatus } from 'dbaas/screens/Plans/constant'
import useStores from 'dbaas/stores/useStores'

import { AwsVpcPeerCreationModal, AWSVPCPeeringList } from './aws'
import { GcpVpcPeerCreationModal, GCPVPCPeeringList } from './gcp'

export const VPCPeeringHome = observer(() => {
  const {
    store: {
      tenantData: { third_party_account_provider, plan }
    }
  } = useStores()
  const limitedProvider = [CloudProviderConst.AWS, CloudProviderConst.GCP].find((p) =>
    third_party_account_provider.toLowerCase().includes(p)
  )

  const [urlState, setUrlState] = useUrlState({ provider: limitedProvider || CloudProviderConst.AWS })
  const currentProvider: NonNullable<typeof limitedProvider> = urlState.provider

  const [awsCreationOpened, awsCreationHandlers] = useDisclosure(false)
  const [gcpCreationOpened, gcpCreationHandlers] = useDisclosure(false)
  const creationHandlers = {
    [CloudProviderConst.AWS]: awsCreationHandlers,
    [CloudProviderConst.GCP]: gcpCreationHandlers
  }

  return (
    <Stack justify="flex-start">
      {plan !== OrgPlanStatus.ON_DEMAND && (
        <Alert>
          <strong>Tips: </strong>To have a VPC Peering connection for your cluster, you need to{' '}
          <AccessGuard id="ClusterCreationGate" fallback="create a Dedicated cluster">
            <Link
              to="/clusters/create-cluster?tier=dedicated"
              data-mp-event="Create a Dedicated Tier Cluster Link Clicked"
            >
              create a Dedicated cluster
            </Link>
          </AccessGuard>{' '}
          first.
        </Alert>
      )}
      <Alert color="yellow">
        VPC Peering is not supported for TiDB Cloud on Azure. To establish a more secure and reliable connection, we
        recommend using Private Endpoint.
      </Alert>
      {!limitedProvider && (
        <Group justify="space-between">
          <SegmentedControl
            value={currentProvider}
            onChange={(value) => setUrlState({ provider: value })}
            data={[
              { label: CloudProviderLabelConst.aws, value: CloudProviderConst.AWS },
              { label: CloudProviderLabelConst.gcp, value: CloudProviderConst.GCP }
            ]}
            py={5}
          />
          <AccessDeniedHoverHint id="ProjectNetworkAction">
            {({ accessible }) => (
              <>
                {urlState.provider === CloudProviderConst.AWS && (
                  <Button
                    size="sm"
                    disabled={!accessible}
                    onClick={awsCreationHandlers.open}
                    data-mp-event="Click AWS VPC Peering Creation Menu Item"
                  >
                    Create VPC Peering
                  </Button>
                )}
                {urlState.provider === CloudProviderConst.GCP && (
                  <Button
                    size="sm"
                    disabled={!accessible}
                    onClick={gcpCreationHandlers.open}
                    data-mp-event="Click Google Cloud VPC Peering Creation Menu Item"
                  >
                    Create VPC Peering
                  </Button>
                )}
              </>
            )}
          </AccessDeniedHoverHint>
        </Group>
      )}
      {limitedProvider && (
        <AccessDeniedHoverHint id="ProjectNetworkAction">
          {({ accessible }) => (
            <Group justify="space-between">
              <Button
                disabled={!accessible}
                onClick={creationHandlers[currentProvider]?.open}
                data-mp-event={`Create ${currentProvider} VPC Peering button clicked`}
              >
                Create VPC Peering
              </Button>
            </Group>
          )}
        </AccessDeniedHoverHint>
      )}
      <Box mx="-xl">
        {currentProvider === CloudProviderConst.AWS && <AWSVPCPeeringList />}
        {currentProvider === CloudProviderConst.GCP && <GCPVPCPeeringList />}
      </Box>
      <AwsVpcPeerCreationModal
        opened={awsCreationOpened}
        onClose={awsCreationHandlers.close}
        onConfirm={() => setUrlState({ provider: CloudProviderConst.AWS })}
      />
      <GcpVpcPeerCreationModal
        opened={gcpCreationOpened}
        onClose={gcpCreationHandlers.close}
        onConfirm={() => setUrlState({ provider: CloudProviderConst.GCP })}
      />
    </Stack>
  )
})
