import { Group, Typography } from '@tidbcloud/uikit'
import { FormTextInput } from '@tidbcloud/uikit/biz'
import { useFormContext } from 'react-hook-form'

import { DataflowDispatchType } from 'dbaas/services/dataflow/interface'

export function FormTopicFormat({ name }: { name: string }) {
  const { watch } = useFormContext()
  const type = watch(`${name}.dispatch_type`)
  const isByTable = type === DataflowDispatchType.DISPATCH_TYPE_BY_TABLE
  const isByDatabase = type === DataflowDispatchType.DISPATCH_TYPE_BY_DATABASE
  const prefix = watch(`${name}.topic_prefix`)
  const separator = watch(`${name}.separator`)
  const suffix = watch(`${name}.topic_suffix`)

  return (
    <>
      <Group justify="space-between">
        <FormTextInput label="Topic Prefix" name={`${name}.topic_prefix`} placeholder="Enter prefix" sx={{ flex: 1 }} />

        {isByTable && (
          <FormTextInput label="Separator" name={`${name}.separator`} placeholder="Enter separator" sx={{ flex: 1 }} />
        )}

        <FormTextInput
          label="Topic Suffix"
          name={`${name}.topic_suffix`}
          placeholder="Enter separator"
          sx={{ flex: 1 }}
        />
      </Group>

      <Typography c="carbon.7" variant="body-lg">
        For example, a table in `db1` named `tbl2` will have its row change events sent to topic:
        <Typography span ml={4} fw={500}>
          {[prefix, ...(isByDatabase ? ['db1'] : ['db1', separator, 'tbl2']), suffix]
            .filter(Boolean)
            .map((i, index) => {
              if (index % 2 === 0) {
                return (
                  <Typography span c="cyan.6">
                    {i}
                  </Typography>
                )
              }
              return <span>{i}</span>
            })}
        </Typography>
      </Typography>
    </>
  )
}
