import { Modal, Button, Typography, Group, Stack, Code, notifier } from '@tidbcloud/uikit'

import { getApiErrorMsgDom } from 'dbaas/components/Notification/ErrorMessag'
import { CloudProviderConst } from 'dbaas/features/Project'
import { usePrivateEndpointConnectionServiceDeletePrivateEndpointConnection } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import useStores from 'dbaas/stores/useStores'
import { MixpanelEvents } from 'dbaas/utils/tracking'

interface DeletePremiumAwsPrivateEndpointModalProps {
  tidbId: string
  connectionId: string
  endpointName: string
  opened: boolean
  onClose: () => void
  onFinish?: () => void
}

export const DeletePremiumAwsPrivateEndpointModal = ({
  tidbId,
  connectionId,
  endpointName,
  opened,
  onClose,
  onFinish
}: DeletePremiumAwsPrivateEndpointModalProps) => {
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()
  const mutator = usePrivateEndpointConnectionServiceDeletePrivateEndpointConnection({
    mutation: {
      onSuccess: () => {
        notifier.success('AWS Private Endpoint deleted successfully')
        onFinish?.()
        onClose()
      },
      onError: (error) => {
        const errorMsgDom = getApiErrorMsgDom(error)

        notifier.error(errorMsgDom)
      }
    }
  })

  const handleDelete = async () => {
    return mutator.mutateAsync({
      tidbId,
      privateEndpointConnectionId: connectionId,
      params: { orgId, projectId }
    })
  }

  return (
    <Modal title="Delete AWS Private Endpoint" centered size={480} opened={opened} onClose={onClose}>
      <Stack>
        <Stack gap={8}>
          <Typography variant="label-lg">Private Endpoint</Typography>
          <Code fz={13} fw={600} bg="carbon.3" c="carbon.9" style={{ wordBreak: 'break-word' }}>
            {endpointName}
          </Code>
        </Stack>
        <Typography variant="body-lg">
          Are you sure you want to delete this private endpoint connection? Deleted information cannot be recovered.
        </Typography>
        <Group justify="flex-end">
          <Button
            variant="default"
            onClick={onClose}
            data-mp-event={MixpanelEvents.PremiumPrivateEndpoint.Delete.CancelClicked}
            data-mp-cloud-provider={CloudProviderConst.AWS}
          >
            Cancel
          </Button>
          <Button
            color="red"
            variant="light"
            loading={mutator.isLoading}
            onClick={handleDelete}
            data-mp-event={MixpanelEvents.PremiumPrivateEndpoint.Delete.SubmitClicked}
            data-mp-cloud-provider={CloudProviderConst.AWS}
          >
            I understand, delete it
          </Button>
        </Group>
      </Stack>
    </Modal>
  )
}
