import { notifier } from '@tidbcloud/uikit'
import { FormMultiSelect } from '@tidbcloud/uikit/biz'
import { useEffect } from 'react'
import { useFormContext } from 'react-hook-form'

import { getErrorMessage } from 'dbaas/services/errorCodes'
import { useGetVercelProjects } from 'dbaas/services/vercel'
import useQuery from 'dbaas/utils/useQuery'

const Step1 = (props: { vercelProChanged?: (values: string[]) => void }) => {
  const query = useQuery()
  const currentProjectId = query.get('currentProjectId')
  const configurationId = query.get('configurationId')
  const { setValue } = useFormContext()

  const { data } = useGetVercelProjects(configurationId || '', {
    query: {
      enabled: !!configurationId,
      refetchInterval: false,
      refetchOnWindowFocus: false,
      onError: (error) => {
        notifier.error(getErrorMessage(error))
      },
      onSuccess: (data) => {
        if (!data?.projects?.length) {
          return
        }

        let selectedByQuery
        if (currentProjectId) {
          selectedByQuery = data.projects.find((project) => project.id === currentProjectId)
        }
        if (!selectedByQuery) {
          selectedByQuery = data.projects[0]
        }
        const val = [JSON.stringify(selectedByQuery)]
        setValue('vercelProjects', val)

        onChange(val)
      }
    }
  })

  useEffect(() => {
    if (!configurationId) {
      notifier.error('exchange token failed')
      return
    }
  }, [configurationId])

  const onChange = (values: string[]) => {
    props.vercelProChanged && props.vercelProChanged(values)
  }

  return (
    <FormMultiSelect
      multiple
      clearable
      required
      name="vercelProjects"
      label="Vercel Projects"
      placeholder="Select project"
      data={
        data?.projects?.map((project) => ({
          label: project.name || '',
          value: JSON.stringify(project)
        })) || []
      }
      styles={{
        pillsList: {
          overflow: 'hidden',
          flexWrap: 'nowrap'
        },
        pill: {
          maxWidth: '30%'
        }
      }}
      onChange={onChange}
    />
  )
}

export default Step1
