import { Box, Button, Group } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import React, { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { useMutation } from 'react-query'

import { deletePrivateLinkEndpoint, createPrivateLinkEndpoint, CentralPrivateLinkServiceStatus } from 'dbaas/services'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'
import EndpointIdInstruction from 'media/endpoint-id-instruction.png'

import Instruction from '../Components/Instruction'

type FormValues = { vpc_endpoint_id: string }

const FormItems = ({}: { accepted: boolean; initEndpointId: string }) => {
  return (
    <Box>
      <FormTextInput
        name="vpc_endpoint_id"
        placeholder="vpce-xxxxxxxx"
        label="Your VPC Endpoint ID"
        rules={{
          pattern: {
            value: /^vpce-[a-z0-9]{17}$/,
            message: `Please enter a valid VPC Endpoint ID.`
          }
        }}
      ></FormTextInput>
      <Instruction
        title="The is a 22 character string in the Endpoints dashboard in AWS Account."
        imageSrc={EndpointIdInstruction}
      />
    </Box>
  )
}

export default ({
  clusterId,
  initEndpointId,
  accepted,
  onPrev,
  onNext,
  cancel
}: {
  clusterId: string
  region?: string
  serviceName?: string
  serviceStatus?: CentralPrivateLinkServiceStatus
  initEndpointId: string
  accepted: boolean
  onPrev: () => void
  onNext: (vpc_endpoint_id: string) => void
  cancel: React.ReactNode
}) => {
  const {
    store: { tenantData, activeProjectId }
  } = useStores()

  const formProps = useForm<FormValues>()
  const { watch, setValue, getValues } = formProps

  useEffect(() => {
    setValue('vpc_endpoint_id', initEndpointId)
  }, [initEndpointId])

  const onSubmit = async (values: FormValues) => {
    if (values.vpc_endpoint_id === initEndpointId) {
      onNext(values.vpc_endpoint_id)
    } else {
      mutation.mutate({ vpc_endpoint_id: values.vpc_endpoint_id })
    }
  }

  const mutation = useMutation(
    async ({ vpc_endpoint_id }: { vpc_endpoint_id: string }) => {
      return createPrivateLinkEndpoint(tenantData.id, activeProjectId, clusterId, {
        cloud_provider: 'aws',
        endpoint_name: vpc_endpoint_id
      }).then(() => {
        if (initEndpointId) {
          return deletePrivateLinkEndpoint(tenantData.id, activeProjectId, clusterId, initEndpointId)
        }
      })
    },
    {
      onSuccess: () => {
        eventTracking('Created A Private Endpoint')
        const values = getValues()
        onNext(values.vpc_endpoint_id)
      },
      onError: (error) => {
        // An error happened!
        console.log(error)
      }
    }
  )

  return (
    <Form<FormValues> form={formProps} withActions={false} onSubmit={onSubmit}>
      <FormItems accepted={accepted} initEndpointId={initEndpointId} />
      <Group justify="flex-end" mt={24}>
        {cancel}
        <Button variant="default" data-mp-event="Accept Endpoint Connection Back Button Clicked" onClick={onPrev}>
          Back
        </Button>
        <Button
          type="submit"
          loading={mutation.isLoading}
          disabled={!watch('vpc_endpoint_id') || mutation.isLoading || mutation.isError}
          data-mp-event="Accept Endpoint Connection Next Button Clicked"
        >
          Next
        </Button>
      </Group>
    </Form>
  )
}
