import { Divider, Group, Loader, Stack } from '@tidbcloud/uikit'
import { FormPasswordInput, FormSelect, FormTextInput } from '@tidbcloud/uikit/biz'
import { useMemo } from 'react'
import { Controller, useFormContext } from 'react-hook-form'

import { useIsEditingChangefeed } from 'dbaas/features/Changefeed'
import { getChangefeedClusterMetadata } from 'dbaas/features/Changefeed/types'
import type { SharedTiDB } from 'dbaas/screens/NextGen/shared/model/shared-tidb-state'
import { useServerlessServiceListClusters } from 'dbaas/services/api-clients/v2023/serverless/v1beta1'

export function FormTiDBServerless({
  orgId,
  projectId,
  cluster
}: {
  orgId: string
  projectId: string
  cluster: SharedTiDB
}) {
  const isEditing = useIsEditingChangefeed()
  const { control } = useFormContext()
  const { regionId } = useMemo(() => getChangefeedClusterMetadata(cluster), [cluster])
  const { data: clustersData, isLoading: isLoadingClusterOptions } = useServerlessServiceListClusters(
    {
      orgId,
      projectId,
      skip: 0,
      pageSize: 100,
      filter: `region.name="${regionId}" AND state="ACTIVE"`
    },
    {
      query: {
        refetchOnWindowFocus: false
      }
    }
  )

  const serverlessClusterOptions = useMemo(() => {
    return (
      (clustersData?.clusters || []).map((i) => ({
        label: i?.displayName || '',
        value: i?.clusterId || ''
      })) ?? []
    )
  }, [clustersData])

  return (
    <>
      <Divider />
      <Stack m={24} maw={1000}>
        <Controller
          name="tidb.mysql_info.privatelink_info.df_privatelink_endpoint_id"
          control={control}
          render={({ field }) => <input {...field} hidden />}
        />

        <FormSelect
          label="Cluster"
          name="tidb.cluster_id"
          rules={{ required: 'Required' }}
          data={serverlessClusterOptions}
          disabled={isEditing}
          rightSection={isLoadingClusterOptions ? <Loader size="xs" /> : undefined}
          placeholder="Select a cluster"
          inputWrapperOrder={['label', 'input', 'description', 'error']}
          description={
            serverlessClusterOptions.length === 0
              ? `Only active clusters in the same region (${regionId}) are available here.`
              : undefined
          }
        />

        <Group>
          <FormTextInput
            name="tidb.mysql_info.connection.username"
            label="User Name"
            rules={{ required: 'Required' }}
            placeholder="Enter the user name"
            sx={() => ({ flex: 1 })}
          />

          <FormPasswordInput
            name="tidb.mysql_info.connection.password"
            label="Password"
            placeholder="Enter the password"
            sx={() => ({ flex: 1 })}
          />
        </Group>
      </Stack>
    </>
  )
}
