import { Button, Card, Flex, Stack, Typography, TypographyProps, notifier } from '@tidbcloud/uikit'
import { useMemoizedFn } from 'ahooks'
import { observer } from 'mobx-react'
import { useFormContext } from 'react-hook-form'
import { useHistory } from 'react-router-dom'

import { PropertyKV } from 'dbaas/components'
import { getApiErrorMsgDom } from 'dbaas/components/Notification/ErrorMessag'
import { getCloudProviderLabel } from 'dbaas/features/Project'
import { queryClient } from 'dbaas/reactQueryClient'
import { SharedTiDB } from 'dbaas/screens/NextGen/shared/model/shared-tidb-state'
import { getDisplayServicePlan } from 'dbaas/screens/NextGen/shared/tidb-instance/service-plan/ServicePlanTag'
import {
  getTidbServiceGetTidbQueryKey,
  useTidbServiceUpdateTidb
} from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import { Commonv1beta1ServicePlan } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'
import { MixpanelEvents } from 'dbaas/utils/tracking'

import { EditFormValueState, useCancel } from './helpers'
import { invalidateCapacityLimitsQueries } from './shared/use-capacity-limits'

interface SumInfoItemProps {
  label: string
  value?: React.ReactNode
  isError?: boolean
  errors?: React.ReactNode
  labelProps?: TypographyProps
}

export const SumInfoItem = ({ label, value = '', isError, errors, labelProps = {} }: SumInfoItemProps) => {
  return (
    <PropertyKV
      label={label}
      labelProps={{
        w: 112,
        ...labelProps
      }}
      valueProps={{ color: isError ? 'red' : 'carbon.8' }}
    >
      {isError ? (errors ?? `Invalid ${label}`) : value}
    </PropertyKV>
  )
}

const PremiumCost = () => {
  return (
    <Stack gap={4} mt={24}>
      <Typography variant="title-lg">Estimated cost</Typography>
      <Typography variant="body-lg">In Early Bird Program</Typography>

      {/* <Flex align="center">
        <Typography variant="headline-md" mr={4}>
          Not Available
        </Typography>
        <HoverCard shadow="md" withArrow withinPortal position="top">
          <HoverCard.Target>
            <IconInfoCircle cursor="pointer" size={16} color="carbon.8" />
          </HoverCard.Target>
          <HoverCard.Dropdown>
            <Typography variant="body-lg">Price estimation is not ready in Private Preview.</Typography>
          </HoverCard.Dropdown>
        </HoverCard>
      </Flex> */}
    </Stack>
  )
}

interface SumCardProps {
  tidb: SharedTiDB
  disabled?: boolean
}

export const SumCard = observer(({ tidb, disabled }: SumCardProps) => {
  const planLabel = tidb.computed.isCassandra ? 'Cassandra Integration' : getDisplayServicePlan(tidb.servicePlan)
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()
  const cancel = useCancel()
  const history = useHistory()
  const {
    handleSubmit,
    formState: { errors }
  } = useFormContext<EditFormValueState>()

  const updator = useTidbServiceUpdateTidb({
    mutation: {
      onSuccess: () => {
        if (tidb.tidbId) {
          notifier.success('Capacity updated successfully!')
          queryClient.invalidateQueries(
            getTidbServiceGetTidbQueryKey(tidb.tidbId || '', {
              orgId,
              projectId
            })
          )
          // Invalidate capacity limits queries to refresh quota data
          invalidateCapacityLimitsQueries(queryClient, tidb.servicePlan, orgId, projectId)
          history.push(`/tidbs/${tidb.tidbId}/overview`)
        }
      },
      onError: (error) => {
        const errorMsgDom = getApiErrorMsgDom(error)

        notifier.error(errorMsgDom)
      }
    }
  })
  const onSubmit = useMemoizedFn(async (data: EditFormValueState) => {
    if (!orgId || !tidb?.tidbId) {
      notifier.error(<div dangerouslySetInnerHTML={{ __html: 'Failed to update instance plan' }}></div>)
      return
    }
    return await updator.mutateAsync({
      tidbId: tidb.tidbId,
      data: {
        maxRcu: data.maxRcu.toString()
      },
      params: {
        orgId,
        projectId
      }
    })
  })
  const onConfirm = handleSubmit(onSubmit)

  return (
    <Card shadow="none" p="xl" miw={400}>
      <Typography variant="title-lg">Summary</Typography>
      <Typography variant="body-lg" c="carbon.7" mt={4}>
        Your new plan will be
      </Typography>

      <Stack justify="flex-start" gap={8} pt="xl">
        <SumInfoItem label="Plan" value={planLabel} />
        <SumInfoItem label="Provider" value={getCloudProviderLabel(tidb.cloudProvider)} />
        <SumInfoItem label="Region" value={tidb.regionDisplayName} />
        <SumInfoItem label="Name" value={tidb.displayName} />
      </Stack>
      <PremiumCost />
      <Flex align="center" gap="md" mt="xl">
        <Button
          variant="default"
          onClick={cancel}
          data-mp-event={MixpanelEvents.TidbCapacity.Update.CancelClicked}
          data-mp-service-plan={Commonv1beta1ServicePlan.Premium}
        >
          Cancel
        </Button>
        <Button
          disabled={disabled || !!errors?.maxRcu}
          loading={updator.isLoading}
          onClick={onConfirm}
          sx={{ flexGrow: 1 }}
          data-mp-event={MixpanelEvents.TidbCapacity.Update.SubmitClicked}
          data-mp-service-plan={Commonv1beta1ServicePlan.Premium}
        >
          Update Capacity
        </Button>
      </Flex>
    </Card>
  )
})
