import { zodResolver } from '@hookform/resolvers/zod'
import { notifier } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
import { useCallback, useId } from 'react'
import { FormProvider, useForm } from 'react-hook-form'
import { useHistory, useLocation } from 'react-router-dom'

import { markOneConsoleFeedbackEventCompleted } from 'dbaas/layouts/v5/NewNavGuide/feedbackState'
import { useCreateResourceRoleState } from 'dbaas/screens/NextGen/shared/access/create-resource-role'
import { V1beta2TidbHighAvailabilityType } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'

import { TwoPaneLayout } from '../../layout/TwoPaneLayout'
import { useVirtualProjectId } from '../../shared/use-virtual-project-id'

import { EssentialV2Form } from './EssentialV2Form'
import { EssentialV2Summary } from './EssentialV2Summary'
import { createEssentialV2FormSchema, ESSENTIAL_V2_RCU_MIN } from './schema'
import { EssentialV2FormValue } from './types'
import { useCreateEssentialV2 } from './use-create-essential-v2'

interface EssentialV2CreationProps {
  header: React.ReactNode
  planSelector: React.ReactNode
  active: boolean
}

export const EssentialV2Creation = observer(({ header, planSelector, active }: EssentialV2CreationProps) => {
  const history = useHistory()
  const location = useLocation()
  const {
    store: {
      userProfile: { id: userId },
      lastVisitLocation: { orgId }
    },
    actions: { refreshOrgData }
  } = useStores()

  const virtualProjectId = useVirtualProjectId()
  const { requiresProjectSelection, isOrgOwner } = useCreateResourceRoleState()

  const formMethods = useForm<EssentialV2FormValue>({
    mode: 'onChange',
    defaultValues: {
      projectId: '',
      provider: '',
      region: '',
      name: '',
      // Dual-layer data encryption section is temporarily hidden for Essential V2.
      // Keep the default disabled until the section is enabled again.
      encrypted: false,
      minRcu: ESSENTIAL_V2_RCU_MIN,
      maxRcu: 10000,
      highAvailabilityType: V1beta2TidbHighAvailabilityType.REGIONAL
    },
    resolver: (values, ctx, options) => {
      const resolvedProjectId = isOrgOwner ? values.projectId || virtualProjectId : values.projectId
      const schema = createEssentialV2FormSchema(orgId, resolvedProjectId, {
        requireProjectSelection: requiresProjectSelection
      })

      return zodResolver(schema)(values, ctx, options)
    }
  })

  const { createTidb, isCreating } = useCreateEssentialV2({
    onSuccess: (tidbId) => {
      refreshOrgData()
      markOneConsoleFeedbackEventCompleted(userId, 'creation')
      notifier.success('Creating TiDB Cloud Essential Instance...')
      if (tidbId) {
        history.push(`/tidbs/${tidbId}/overview${location.search}`)
      } else {
        history.push(`/tidbs${location.search}`)
      }
    },
    onError: (errorMsg) => {
      notifier.error(<div dangerouslySetInnerHTML={{ __html: errorMsg }} />)
    }
  })

  const handleValidSubmit = useCallback(
    async (data: EssentialV2FormValue) => {
      const resolvedProjectId = isOrgOwner ? data.projectId || virtualProjectId : data.projectId

      await createTidb({
        ...data,
        projectId: resolvedProjectId
      })
    },
    [createTidb, isOrgOwner, virtualProjectId]
  )
  const formId = useId()

  return (
    <FormProvider {...formMethods}>
      <TwoPaneLayout
        visible={active}
        header={header}
        rightSection={<EssentialV2Summary formId={formId} isPending={isCreating} />}
      >
        <EssentialV2Form
          formId={formId}
          planSelector={planSelector}
          onSubmit={formMethods.handleSubmit(handleValidSubmit)}
        />
      </TwoPaneLayout>
    </FormProvider>
  )
})
