import { Modal, Button, Typography, Group, Stack, notifier, TextInput } 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 DeletePremiumAliPrivateEndpointModalProps {
  tidbId: string
  connectionId: string
  resourceId: string
  serviceName: string
  opened: boolean
  onClose: () => void
  onFinish?: () => void
}

export const DeletePremiumAliPrivateEndpointModal = ({
  tidbId,
  connectionId,
  resourceId,
  serviceName,
  opened,
  onClose,
  onFinish
}: DeletePremiumAliPrivateEndpointModalProps) => {
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()
  const mutator = usePrivateEndpointConnectionServiceDeletePrivateEndpointConnection({
    mutation: {
      onSuccess: () => {
        notifier.success('Ali Private Endpoint Connection 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 Alibaba Cloud Private Endpoint Connection"
      centered
      size={560}
      opened={opened}
      onClose={onClose}
    >
      <Stack>
        <TextInput value={resourceId} disabled label="Alibaba Cloud Private Endpoint Resource ID" />
        <TextInput value={serviceName} disabled label="TiDB PrivateLink Service" />
        <Typography variant="body-lg">
          Are you sure to delete the connection between the Alibaba Cloud Private Endpoint resource and TiDB PrivateLink
          service?
        </Typography>
        <Group justify="flex-end">
          <Button
            variant="default"
            onClick={onClose}
            data-mp-event={MixpanelEvents.PremiumPrivateEndpoint.Delete.CancelClicked}
            data-mp-cloud-provider={CloudProviderConst.ALICLOUD}
          >
            Cancel
          </Button>
          <Button
            color="red"
            variant="light"
            loading={mutator.isLoading}
            onClick={handleDelete}
            data-mp-event={MixpanelEvents.PremiumPrivateEndpoint.Delete.SubmitClicked}
            data-mp-cloud-provider={CloudProviderConst.ALICLOUD}
          >
            I understand, delete it
          </Button>
        </Group>
      </Stack>
    </Modal>
  )
}
