import { Box, Card, Flex } from '@tidbcloud/uikit'
import { useEffect } from 'react'
import { FormProvider, useForm } from 'react-hook-form'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { PageShell } from 'dbaas/layouts/v5/page'

import { ClusterPlanField } from './ClusterPlanField'
import { EditFormValueState } from './helpers'
import { SumCard } from './SumCard'

export const ClusterPlanEdit = ({ cluster }: { cluster: SharedCluster }) => {
  const formProps = useForm<EditFormValueState>({
    mode: 'onChange',
    defaultValues: {
      autoScaling: {
        minRcu: cluster.autoScaling?.minRcu,
        maxRcu: cluster.autoScaling?.maxRcu
      }
    }
  })
  const { setValue } = formProps

  useEffect(() => {
    if (
      !cluster.computed.loading &&
      cluster.autoScaling?.minRcu !== undefined &&
      cluster.autoScaling?.maxRcu !== undefined
    ) {
      setValue('autoScaling.minRcu', cluster.autoScaling.minRcu)
      setValue('autoScaling.maxRcu', cluster.autoScaling.maxRcu)
    }
  }, [cluster.computed.loading, cluster.autoScaling?.minRcu, cluster.autoScaling?.maxRcu, setValue])

  return (
    <FormProvider {...formProps}>
      <Box h="100vh" sx={{ maxWidth: 1248, margin: '0 auto' }}>
        <PageShell title="Update capacity" headerProps={{ withBack: true }}>
          <Flex gap={16}>
            <Card shadow="none" p="xl" sx={{ alignSelf: 'baseline' }}>
              <Box component="form" sx={{ position: 'relative' }}>
                <ClusterPlanField />
              </Box>
            </Card>
            <Box>
              <SumCard cluster={cluster} />
            </Box>
          </Flex>
        </PageShell>
      </Box>
    </FormProvider>
  )
}
