import { Button, Loader, Card, Flex, Input, Typography, Grid } from '@tidbcloud/uikit'
import { CodeBlock } from '@tidbcloud/uikit/biz'
import { IconCheck } from '@tidbcloud/uikit/icons'
import React, { useState } from 'react'
import { useQuery } from 'react-query'

import { CentralPrivateLinkServiceStatus, getPrivateLinkService } from 'dbaas/services'
import useStores from 'dbaas/stores/useStores'
import SubnetIdsInstruction from 'media/subnet-ids-instruction.png'
import VPCIdInstruction from 'media/vpc-id-instruction.png'

import Instruction from '../Components/Instruction'

export default ({
  clusterId = '',
  region,
  initInfo,
  onPrev,
  onNext,
  cancel
}: {
  clusterId: string
  region: string
  initInfo: { vpc_id: string; subnet_ids: string }
  onPrev: () => void
  onNext: (data: { vpc_id: string; subnet_ids: string }) => void
  cancel: React.ReactNode
}) => {
  const {
    store: { tenantData, activeProjectId }
  } = useStores()

  const { data, isLoading } = useQuery(
    `${clusterId}_private_endpoint`,
    async () => {
      return getPrivateLinkService(tenantData.id, activeProjectId, clusterId).then((data) => data.privatelink_service)
    },
    {
      refetchInterval: (data) => (data?.status !== CentralPrivateLinkServiceStatus.ACTIVE ? 5 * 1000 : false)
    }
  )

  const [vpcId, setVpcId] = useState(initInfo.vpc_id || '')
  const [subnetIds, setSubnetIds] = useState(initInfo.subnet_ids || '')
  const displaySubnetIds = subnetIds ? subnetIds.replace(/\s*,\s*/g, ' ') : '<your_application_subnet_ids>'
  const code = `aws ec2 create-vpc-endpoint --vpc-id ${vpcId} --region ${region} --service-name ${
    data?.name || '<your_vpc_endpoint_service_name>'
  } --vpc-endpoint-type Interface --subnet-ids ${displaySubnetIds}`

  const handleNext = () => {
    onNext({
      vpc_id: vpcId,
      subnet_ids: subnetIds
    })
  }

  return (
    <>
      <div className="step-content">
        {isLoading ? null : (
          <Card pt={10} mb={15}>
            {data?.status === CentralPrivateLinkServiceStatus.ACTIVE ? (
              <Flex align="center" mb={10}>
                <IconCheck color="green" />
                <Typography variant="title-lg" mt={6} ml={5}>
                  Endpoint Service Ready
                </Typography>
              </Flex>
            ) : (
              <Flex align="center" mb={10}>
                <Loader size={20}></Loader>
                <Typography variant="title-lg" mx={10}>
                  Creating Endpoint Service
                </Typography>
                <Typography variant="action-lg" c="blue">
                  This might take 3~4 minutes to process
                </Typography>
              </Flex>
            )}
            <p>
              While TiDB Endpoint Service is being created, we will need to gather your application VPC ID and Subnet
              IDs to help you create your application VPC Interface Endpoint.
            </p>
          </Card>
        )}

        <form id="interface-endpoint" onSubmit={(e) => e.preventDefault()}>
          <Grid>
            <Grid.Col span={6}>
              <Typography variant="label-lg" mb={8}>
                Your VPC ID
              </Typography>
              <Input
                mb={5}
                value={vpcId}
                placeholder="VPC ID"
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setVpcId(e.currentTarget.value)}
              />
              <Instruction title="The List of VPCs in the VPC dashboard in AWS Account." imageSrc={VPCIdInstruction} />
            </Grid.Col>
            <Grid.Col span={6}>
              <Typography variant="label-lg" mb={8}>
                Your Subnet IDs
              </Typography>
              <Input
                mb={5}
                value={subnetIds}
                placeholder="Subnet-xx1, Subnet-xx2"
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSubnetIds(e.currentTarget.value)}
              />
              <Instruction
                title="The List of Subnets in the Subnet dashboard in AWS
                      Account."
                imageSrc={SubnetIdsInstruction}
              />
            </Grid.Col>
          </Grid>
          <div>
            <Typography variant="headline-sm" mb={20}>
              After the Endpoint Service is created, run this command with aws-cli to create your VPC Interface Endpoint
            </Typography>
            <CodeBlock language="bash">{code}</CodeBlock>
          </div>
        </form>
      </div>
      <div className="step-actions">
        {cancel}
        <div>
          <Button variant="default" data-mp-event="Creating Endpoint Service Back Button Clicked" onClick={onPrev}>
            Back
          </Button>
          <Button
            disabled={data?.status !== CentralPrivateLinkServiceStatus.ACTIVE}
            type="button"
            data-mp-event="Creating Endpoint Service Next Button Clicked"
            onClick={handleNext}
          >
            Next
          </Button>
        </div>
      </div>
    </>
  )
}
