import { Button, notifier } from '@tidbcloud/uikit'
import { useMemoizedFn } from 'ahooks'
import { useFormContext } from 'react-hook-form'

import { useCreationFinished } from 'dbaas/screens/ClustersV2/new/Serverless/helpers'
import { Commonv1beta1ServicePlan } from 'dbaas/services/api-clients/v2023/serverless/v1beta1/interface'

import { EssentialFormValue } from '../essential'
import { StarterFormValue } from '../starter'

import { useCreateCluster } from './helper'

interface CreateButtonProps {
  disabled?: boolean
  loading?: boolean
  buttonText?: string
  type?: Commonv1beta1ServicePlan
}

export const CreateButton = ({
  disabled,
  loading,
  buttonText,
  type = Commonv1beta1ServicePlan.Essential
}: CreateButtonProps) => {
  const { handleSubmit } = useFormContext()
  const { createCluster, isCreating } = useCreateCluster()
  const finishCreation = useCreationFinished()

  const onSubmit = useMemoizedFn(async (data) => {
    const { provider, region, name } = data || {}

    const formData = {
      provider,
      region,
      name
    }

    let formatedData = data
    switch (type) {
      case Commonv1beta1ServicePlan.Essential:
        formatedData = data as EssentialFormValue
        formData['encrypted'] = formatedData.encrypted
        formData['highAvailabilityType'] = formatedData.highAvailabilityType
        formData['autoScaling'] = {
          minRcu: formatedData.autoScaling?.minRcu,
          maxRcu: formatedData.autoScaling?.maxRcu
        }
        formData['servicePlan'] = Commonv1beta1ServicePlan.Essential

        break
      case Commonv1beta1ServicePlan.Starter:
        formatedData = data as StarterFormValue
        formData['spendLimit'] = Number(formatedData.spendingLimit)
        formData['encrypted'] = formatedData.encrypted
        formData['servicePlan'] = Commonv1beta1ServicePlan.Starter
        break
    }

    const { clusterId, errorMsg } = await createCluster(formData)

    if (clusterId) {
      finishCreation(clusterId)
    } else if (errorMsg) {
      notifier.error(<div dangerouslySetInnerHTML={{ __html: errorMsg }}></div>)
    }
  })

  const onConfirm = handleSubmit(onSubmit)

  return (
    <Button
      disabled={disabled}
      loading={loading || isCreating}
      sx={{ flexGrow: 1 }}
      data-mp-event="Cluster Creation Button Clicked"
      data-mp-service-plan={type}
      data-mp-source={`Clusters - Creation ${type}`}
      data-testid="standard-cluster-creation-btn"
      onClick={onConfirm}
    >
      {buttonText ? buttonText : loading ? 'Fetching...' : 'Create'}
    </Button>
  )
}
