import { Divider, Group, Input, Loader, Stack } from '@tidbcloud/uikit'
import {
  FormNumberInput,
  FormPasswordInput,
  FormRadioGroup,
  FormSelect,
  FormSwitch,
  FormTextInput
} from '@tidbcloud/uikit/biz'
import { IconLinkExternal02 } from '@tidbcloud/uikit/icons'
import { useFormContext } from 'react-hook-form'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useOrgProjectClusterIds } from 'dbaas/features/Common'
import HeadLabel from 'dbaas/screens/ClustersV2/new/components/HeadLabel'
import { usePrivateLinkConnectionServiceListPrivateLinkConnections } from 'dbaas/services/api-clients/legacy/serverless'
import { MySQLNetworkTypeEnum } from 'dbaas/services/api-clients/legacy/serverless/interface'

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

const NETWORK_TYPE_OPTIONS = [
  { label: 'Public', value: MySQLNetworkTypeEnum.PUBLIC },
  { label: 'Private Link', value: MySQLNetworkTypeEnum.PRIVATE_LINK }
]

export const FormMySQLEssential = ({ cluster }: { cluster: SharedCluster }) => {
  const { orgId, projectId } = useOrgProjectClusterIds()

  const { watch } = useFormContext<CreateOrEditChangefeedEssentialFormData>()
  const networkType = watch('mysql.network.network_type')

  const { data: privateLinkConnections, isLoading: isLoadingPrivateLinkConnections } =
    usePrivateLinkConnectionServiceListPrivateLinkConnections(
      orgId,
      projectId,
      cluster.id!,
      {
        page_size: 50,
        page_token: '1',
        state: 'ACTIVE'
      },
      {
        query: {
          enabled: networkType === 'PRIVATE_LINK' && !!orgId && !!projectId && !!cluster.id,
          refetchOnWindowFocus: false
        }
      }
    )

  return (
    <Stack p={24} pt={0}>
      <Divider mx={-24} />

      <HeadLabel label="Connection" />

      <FormRadioGroup
        name="mysql.network.network_type"
        label="Connectivity Method"
        data={NETWORK_TYPE_OPTIONS}
        rules={{ required: 'Required' }}
      />

      {networkType === MySQLNetworkTypeEnum.PUBLIC && (
        <FormTextInput
          name="mysql.network.public_endpoint"
          label="MySQL Endpoint"
          description="Enter the MySQL endpoint in the format host:port"
          placeholder="mysql.example.com:3306"
          rules={{ required: 'Required' }}
        />
      )}

      {networkType === MySQLNetworkTypeEnum.PRIVATE_LINK && (
        <Group grow wrap="nowrap" align="flex-start">
          <FormSelect
            name="mysql.network.private_link.private_link_connection_id"
            label="Private Link Connection"
            placeholder="Select a Private Link Connection"
            data={
              privateLinkConnections?.private_link_connections?.map((connection) => ({
                label: connection.display_name,
                value: connection.private_link_connection_id!
              })) || []
            }
            inputWrapperOrder={['label', 'input', 'description', 'error']}
            rightSection={isLoadingPrivateLinkConnections ? <Loader size="xs" /> : null}
            description={
              <span>
                Didn't find one?{' '}
                <a href={`/clusters/${cluster.id}/networking`} target="_blank" rel="noopener noreferrer">
                  create a Private Link Connection here <IconLinkExternal02 sx={{ position: 'relative', top: 1 }} />
                </a>
              </span>
            }
            rules={{ required: 'Required' }}
          />
          <FormNumberInput
            name="mysql.network.private_link.port"
            label="Bootstrap Port"
            placeholder="Enter the port number"
            rules={{ required: 'Required' }}
          />
        </Group>
      )}

      <Divider mx={-24} />

      <HeadLabel label="Authentication" />

      <Group grow align="flex-start">
        <FormTextInput
          name="mysql.authentication.user_name"
          label="Username"
          placeholder="Enter the username"
          rules={{ required: 'Required' }}
        />
        <FormPasswordInput
          name="mysql.authentication.password"
          label="Password"
          type="password"
          placeholder="Enter the password"
          rules={{ required: 'Required' }}
        />
      </Group>

      <Stack gap={8}>
        <Input.Label>TLS Encryption</Input.Label>
        <FormSwitch name="mysql.authentication.enable_tls" />
      </Stack>
    </Stack>
  )
}
