import { Box, Button, Flex, Grid, Select, Tooltip, Typography } from '@tidbcloud/uikit'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'
import React from 'react'
import { useMutation } from 'react-query'

import { FormErrorMessage } from 'dbaas/components/Form'
import {
  CentralPrivateLinkService,
  CentralPrivateLinkServiceStatus,
  CentralRegion,
  createPrivateLinkService,
  useGetPrivateLinkService
} from 'dbaas/services'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

export default ({
  clusterId = '',
  region = '',
  regionList = [],
  isEdit,
  isLoading,
  onPrev,
  onNext,
  cancel
}: {
  clusterId: string
  region: string
  regionList: CentralRegion[]
  isEdit: boolean
  isLoading: boolean
  onPrev: () => void
  onNext: (endpoint?: CentralPrivateLinkService) => void
  cancel?: React.ReactNode
}) => {
  // tricky to generate region list: only selected cluster region available
  const options = regionList
    .filter((r) => r.name === region)
    .map((c) => ({
      label: c.display_name,
      value: c.name
    }))
  const {
    store: {
      tenantData: { id: orgId },
      activeProjectId: projectId
    }
  } = useStores()

  const serviceQuery = useGetPrivateLinkService(orgId, projectId, clusterId, {
    query: {
      select: (data) => data?.privatelink_service,
      refetchOnWindowFocus: false
    }
  })
  const creatable = !serviceQuery.data || serviceQuery.data.status === CentralPrivateLinkServiceStatus.NOT_CONFIGURE

  const mutation = useMutation(
    () => {
      return createPrivateLinkService(orgId, projectId, clusterId, {
        cloud_provider: 'aws'
      })
    },
    {
      onSuccess: (data) => {
        onNext(data?.privatelink_service)
        eventTracking('Created A Private Endpoint Service')
      },
      onError: (error) => {
        // An error happened!
        console.log(error)
      }
    }
  )

  const handleNext = () => {
    if (isEdit || !creatable) {
      onNext()
    } else {
      mutation.mutate()
    }
  }

  return (
    <>
      <div className="step-content">
        {isLoading ? null : (
          <Box>
            <Typography variant="title-lg" mb={8}>
              Select Region
            </Typography>
            <Grid columns={2}>
              <Grid.Col span={1}>
                <Select value={region} searchable nothingFoundMessage="No results found." data={options} />
              </Grid.Col>
              <Grid.Col span={1}>
                <Flex align="center" h="100%">
                  <Box mx={10}>Recommended Region</Box>
                  <Tooltip withArrow label="Select the Region where the cluster is located by default.">
                    <Box component={IconInfoCircle} size={16} c="blue" />
                  </Tooltip>
                </Flex>
              </Grid.Col>
            </Grid>
          </Box>
        )}
      </div>

      {mutation.isError && (
        <FormErrorMessage message={getErrorMessage(mutation.error)} onDismiss={() => mutation.reset()} />
      )}
      <div className="step-actions">
        {cancel}
        <div>
          <Button type="button" variant="default" data-mp-event='"Select Region Back Button Clicked' onClick={onPrev}>
            Back
          </Button>
          <Button
            loading={mutation.isLoading}
            disabled={!region || serviceQuery.isLoading || mutation.isLoading || mutation.isError}
            type="button"
            data-mp-event="Select Region Next Button Clicked"
            onClick={handleNext}
          >
            Next
          </Button>
        </div>
      </div>
    </>
  )
}
