import { Box } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
import { useEffect, useState } from 'react'

import { DelayedPageLoader } from 'dbaas/components/Placeholder'
import { ClusterPageShell } from 'dbaas/screens/ClusterV2/components'
import { useBillingPlanAvailability } from 'dbaas/screens/NextGen/my-tidb-creation/shared/use-billing-plan-availability'
import { Commonv1beta1ServicePlan } from 'dbaas/services/api-clients/v2023/serverless/v1beta1/interface'

import { Essential } from './essential'
import { Starter } from './starter'

export const TiDBNextGen = observer(({ onGenChange }: { onGenChange?: () => void }) => {
  const [plan, setPlan] = useState<Commonv1beta1ServicePlan>(Commonv1beta1ServicePlan.Starter)
  const { planAvailability, isLoading } = useBillingPlanAvailability()
  const isStarterEnabled = planAvailability.Starter.enabled
  const isEssentialEnabled = planAvailability.Essential.enabled

  useEffect(() => {
    if (!isStarterEnabled && isEssentialEnabled) {
      setPlan(Commonv1beta1ServicePlan.Essential)
    }
  }, [isEssentialEnabled, isStarterEnabled])

  if (isLoading) {
    return <DelayedPageLoader delayMs={600} />
  }

  const showStarter = plan === Commonv1beta1ServicePlan.Starter && isStarterEnabled
  const showEssential = plan === Commonv1beta1ServicePlan.Essential || (!isStarterEnabled && isEssentialEnabled)

  return (
    <ClusterPageShell title="Create Cluster" headerProps={{ withBack: true }} bodyProps={{ pb: 96 }}>
      <Box
        sx={{
          display: showStarter ? 'block' : 'none'
        }}
      >
        <Starter onChange={setPlan} onGenChange={onGenChange} />
      </Box>
      <Box sx={{ display: showEssential ? 'block' : 'none' }}>
        <Essential
          onChange={setPlan}
          onGenChange={onGenChange}
          clusterPlanProps={{
            planData: {
              starter: {
                disabled: !isStarterEnabled
              }
            }
          }}
        />
      </Box>
    </ClusterPageShell>
  )
})
