import { Alert, Box, Button, Card, Divider, Group, Stack } from '@tidbcloud/uikit'
import { FormRadioGroup, FormRadioGroupProps } from '@tidbcloud/uikit/biz'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { useFormContext } from 'react-hook-form'

import { ChangefeedNames, useIsEditingChangefeed } from 'dbaas/features/Changefeed'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import HeadLabel from 'dbaas/screens/ClustersV2/new/components/HeadLabel'
import { useChangefeedServiceTestChangefeed } from 'dbaas/services/api-clients/legacy/serverless'
import { ChangefeedTypeEnum } from 'dbaas/services/api-clients/legacy/serverless/interface'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'
import { sleep } from 'dbaas/utils/chore'
import { eventTracking } from 'dbaas/utils/tracking'

import type { CreateOrEditChangefeedEssentialFormData } from '../types'

import { FormKafkaEssential } from './FormKafka'
import { FormMySQLEssential } from './FormMySQL'
import { buildTestChangefeedPayload } from './payloadBuilders'

export const ConfigureTargetEssential = ({
  cluster,
  onFinish,
  onCancel
}: {
  cluster: SharedCluster
  onFinish: () => void
  onCancel: () => void
}) => {
  const {
    store: { tenantData, activeProjectId }
  } = useStores()

  const methods = useFormContext<CreateOrEditChangefeedEssentialFormData>()
  const isEditing = useIsEditingChangefeed()
  const { handleSubmit, watch } = methods
  const type = watch('changefeed_type')

  const testChangefeedMutation = useChangefeedServiceTestChangefeed({
    mutation: { retry: false },
    request: { timeout: 120 * 1000 }
  })

  const TARGETS: FormRadioGroupProps['data'] = [
    {
      label: ChangefeedNames.KAFKA,
      value: ChangefeedTypeEnum.KAFKA,
      disabled: isEditing
    },
    {
      label: ChangefeedNames.MYSQL,
      value: ChangefeedTypeEnum.MYSQL,
      disabled: isEditing
    }
  ]

  const onSubmit = async (data: CreateOrEditChangefeedEssentialFormData) => {
    const payload = buildTestChangefeedPayload(data)
    const isTestEnv = process.env.NODE_ENV === 'test' || window.location.search.includes('e2e-test') || window.E2E_Test
    if (isTestEnv) {
      console.log(payload)
      console.log('[E2E Test]-[CreateChangefeed]-[Step1]-[Payload]-' + JSON.stringify(payload))
      onFinish()
      return
    }
    try {
      // test connection when create or edited password/secrets
      if (!isEditing) {
        await testChangefeedMutation.mutateAsync({
          orgId: tenantData.id,
          projectId: activeProjectId,
          clusterId: cluster.id!,
          data: {
            sink: {
              type: payload.sink.type,
              kafka: payload.sink.kafka,
              mysql: payload.sink.mysql
            }
          }
        })
      }

      await sleep(300)
      onFinish()
    } catch (_e) {
      eventTracking('Failed when precheck in changefeed', {
        'Cluster Type': 'Essential'
      })
    }
  }

  const error = testChangefeedMutation.error

  return (
    <Card p={0}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack m={24} gap={6}>
          <HeadLabel label="Destination" />

          <FormRadioGroup name="changefeed_type" data={TARGETS} sx={{ marginTop: 0 }} />
        </Stack>

        {type === ChangefeedTypeEnum.KAFKA && <FormKafkaEssential cluster={cluster} />}
        {type === ChangefeedTypeEnum.MYSQL && <FormMySQLEssential cluster={cluster} />}

        <Divider mx={-24} />

        {error && (
          <Alert icon={<IconAlertCircle size={16} />} color="red" m={24}>
            <Box
              sx={{ wordBreak: 'break-all' }}
              dangerouslySetInnerHTML={{
                __html: getErrorMessage(error, true)
              }}
            />
          </Alert>
        )}

        <Group m={24} justify="flex-end">
          <Button
            variant="default"
            type="button"
            data-mp-event="Configure Target Cancel Button Clicked"
            onClick={onCancel}
          >
            Cancel
          </Button>
          <Button
            type="submit"
            data-mp-event="Configure Target Next Button Clicked"
            loading={testChangefeedMutation.isLoading}
          >
            Next
          </Button>
        </Group>
      </form>
    </Card>
  )
}
