import { Box, Button, Divider, Flex, HoverCard, Skeleton, Stack, Typography } from '@tidbcloud/uikit'
import { notifier } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
import { useFormContext } from 'react-hook-form'
import { useHistory, useLocation } from 'react-router-dom'

import { PropertyKV } from 'dbaas/components'
import { AccessGuard } from 'dbaas/contexts/access-control'
import { getCloudProviderLabel } from 'dbaas/features/Project'
import { useDualLayerDataEncryptionFeatEnabled } from 'dbaas/screens/NextGen/my-tidb-creation/shared/premium-byoc/dual-layer-data-encryption/use-dual-layer-data-encryption-feat-enabled'
import { useAddCreditCard } from 'dbaas/screens/NextGen/my-tidb-creation/shared/use-add-credit-card'
import { PaymentMethodModal } from 'dbaas/screens/Stripe/PaymentMethod/PaymentMethodModal'
import {
  Commonv1beta1ServicePlan,
  V1beta2TidbHighAvailabilityType
} from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'

import { CreateActionGuard } from '../../shared/CreateActionGuard'

import { EssentialV2Cost } from './summary/EssentialV2Cost'
import { EssentialV2FormValue } from './types'

interface EssentialV2SummaryProps {
  formId: string
  disabled?: boolean
  isPending?: boolean
  regionName?: string
}

const HADescriptions: Record<string, string> = {
  [V1beta2TidbHighAvailabilityType.ZONAL]: 'Zonal',
  [V1beta2TidbHighAvailabilityType.REGIONAL]: 'Regional'
}

const SumInfoItem = ({ label, value, isError }: { label: string; value: React.ReactNode; isError?: boolean }) => {
  return (
    <PropertyKV label={label} labelProps={{ w: 144 }} valueProps={{ c: isError ? 'red' : undefined }}>
      {value}
    </PropertyKV>
  )
}

export const EssentialV2Summary = observer(({ formId, disabled, isPending, regionName }: EssentialV2SummaryProps) => {
  const history = useHistory()
  const location = useLocation()
  const {
    store: {
      userProfile: { projects: allProjects }
    }
  } = useStores()

  const {
    watch,
    formState: { errors, dirtyFields }
  } = useFormContext<EssentialV2FormValue>()
  const provider = watch('provider')
  const region = watch('region')
  const projectId = watch('projectId')
  const name = watch('name')
  const minRcu = watch('minRcu')
  const maxRcu = watch('maxRcu')
  const encrypted = watch('encrypted')
  const highAvailabilityType = watch('highAvailabilityType')
  const { isEnabled: isDataEncryptionFeatEnabled } = useDualLayerDataEncryptionFeatEnabled({
    servicePlan: Commonv1beta1ServicePlan.Essential_V2,
    cloudProvider: provider
  })

  const actionsDisabled = !!disabled

  const { creditCardNeeded, creditCardModalVisible, creditCardModalHandlers } = useAddCreditCard()

  const filledFields = (['provider', 'region', 'name'] as const).filter((key) => !!dirtyFields?.[key]).join(', ')
  const projectName = allProjects?.find((p) => p.id === projectId)?.name ?? '-'
  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      <Box>
        <Typography variant="title-lg">Summary</Typography>
        <Typography variant="body-lg" c="carbon.7" mt={4}>
          Your new instance will be:
        </Typography>

        <Stack justify="flex-start" gap={8} pt="xl" pb="md">
          <SumInfoItem label="Plan" value="Essential" />
          <SumInfoItem label="Project" value={projectName} />
          <SumInfoItem label="Instance Name" value={name || '-'} isError={!!errors?.name} />
          <SumInfoItem label="Cloud Provider" value={getCloudProviderLabel(provider)} />
          <SumInfoItem label="Region" value={regionName || <Skeleton width={120} height={16} />} />
          <Divider my={8} />
          <SumInfoItem label="Min RCUs" value={minRcu ?? '-'} />
          <SumInfoItem label="Max RCUs" value={maxRcu ?? '-'} />
          {isDataEncryptionFeatEnabled && (
            <>
              <Divider my={8} />
              <SumInfoItem label="Dual-Layer Data Encryption" value={encrypted ? 'Enabled' : 'Disabled'} />
            </>
          )}
          <SumInfoItem label="High Availability" value={HADescriptions[highAvailabilityType] || '-'} />
        </Stack>
      </Box>
      <Divider />
      <Box sx={{ marginTop: 'auto' }}>
        <EssentialV2Cost cloudProvider={provider} regionId={region} minRcu={minRcu} maxRcu={maxRcu} />

        <Flex align="center" gap="md">
          <Button
            variant="default"
            onClick={() => history.push(`/tidbs${location.search}`)}
            data-mp-event="Cancel Created A Cluster"
            data-mp-service-plan="Essential"
            data-mp-source="My TiDB - Creation"
            data-mp-filled-fields={filledFields}
          >
            Cancel
          </Button>

          <CreateActionGuard
            projectId={projectId}
            permissionMessage={'Please ask your admin to grant you the permission to create an Essential instance.'}
          >
            {!creditCardNeeded && (
              <Button
                type="submit"
                form={formId}
                disabled={actionsDisabled}
                loading={isPending}
                sx={{ flexGrow: 1 }}
                data-mp-event="Cluster Creation Button Clicked"
                data-mp-service-plan="Essential"
                data-mp-source="My TiDB - Creation"
              >
                Create
              </Button>
            )}
            {creditCardNeeded && (
              <AccessGuard
                id="BillingPaymentCreation"
                fallback={
                  <HoverCard withArrow withinPortal>
                    <HoverCard.Target>
                      <span style={{ flexGrow: 1 }}>
                        <Button
                          disabled
                          sx={{ width: '100%' }}
                          data-mp-event="mp-addcreditcard-1691461017771"
                          data-mp-source="My TiDB - Creation"
                        >
                          Add Credit Card
                        </Button>
                      </span>
                    </HoverCard.Target>
                    <HoverCard.Dropdown maw={320}>
                      Please contact your Organization Owner or Billing Manager to add a credit card.
                    </HoverCard.Dropdown>
                  </HoverCard>
                }
              >
                <Button
                  onClick={creditCardModalHandlers.open}
                  sx={{ flexGrow: 1 }}
                  data-mp-event="Add Credit Card Button Clicked"
                  data-mp-service-plan="Essential"
                  data-mp-source="My TiDB - Creation"
                >
                  Add Credit Card
                </Button>
              </AccessGuard>
            )}
          </CreateActionGuard>
        </Flex>
      </Box>

      {creditCardNeeded && (
        <PaymentMethodModal
          open={creditCardModalVisible}
          onClose={creditCardModalHandlers.close}
          onComplete={() => {
            creditCardModalHandlers.close()
            notifier.success('Your credit card was added successfully!')
          }}
        />
      )}
    </Box>
  )
})
