import { Button, Group, Modal, notifier, Typography } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'

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

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

export const PremiumDisablePublicEndpointModal = observer(
  ({ tidbId, opened, onClose, onFinish }: PremiumDisablePublicEndpointModalProps) => {
    const {
      store: {
        lastVisitLocation: { orgId, projectId }
      }
    } = useStores()
    const updator = usePublicConnectionSettingServiceUpdatePublicConnectionSetting({
      mutation: {
        onSuccess: () => {
          notifier.success('Public endpoint disabled successfully')
          onFinish?.()
          onClose()
        },
        onError: (error) => {
          const errorMsgDom = getApiErrorMsgDom(error)

          notifier.error(errorMsgDom)
        }
      }
    })

    const handleDisable = () => {
      return updator.mutateAsync({
        tidbId,
        data: {
          enabled: false
        },
        params: {
          orgId,
          projectId
        }
      })
    }

    return (
      <Modal title="Disable Public Endpoint" centered size="md" opened={opened} onClose={onClose}>
        <Typography variant="body-lg" mb="xl">
          You are about to disable the public endpoint for your instance. Please note that while this action will not
          impact any existing connections to the public endpoint, it will prevent new connections from being established
          through it.
        </Typography>
        <Group justify="flex-end">
          <Button
            variant="default"
            onClick={onClose}
            data-mp-event={MixpanelEvents.PremiumPublicConnect.Disable.CancelClicked}
          >
            Cancel
          </Button>
          <Button
            variant="light"
            color="red"
            loading={updator.isLoading}
            onClick={handleDisable}
            data-mp-event={MixpanelEvents.PremiumPublicConnect.Disable.SubmitClicked}
          >
            Disable
          </Button>
        </Group>
      </Modal>
    )
  }
)
