import { Alert, AlertProps, Box, Button, Group, notifier } from '@tidbcloud/uikit'
import { IconXCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useQueryClient } from 'react-query'

import {
  getServerlessServiceGetClusterQueryKey,
  useServerlessServiceGetCluster,
  useServerlessServicePartialUpdateCluster
} from 'dbaas/services/api-clients/v2023/serverless/v1beta1'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

interface PublicEndpointAlertProps {
  clusterId: string
  alertProps?: AlertProps
}

export const PublicEndpointAlert = observer(({ clusterId, alertProps }: PublicEndpointAlertProps) => {
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()
  const clusterQuery = useServerlessServiceGetCluster(
    clusterId,
    {
      view: 'BASIC',
      orgId,
      projectId
    },
    {
      query: {
        refetchOnMount: false,
        refetchOnWindowFocus: false
      }
    }
  )
  const cluster = clusterQuery.data

  const queryClient = useQueryClient()
  const mutator = useServerlessServicePartialUpdateCluster({
    mutation: {
      onSuccess: () => {
        queryClient.invalidateQueries(
          getServerlessServiceGetClusterQueryKey(clusterId, {
            view: 'BASIC',
            orgId,
            projectId
          })
        )
        notifier.success("You have enabled this instance's public endpoint successfully.")
      },
      onError: (error) => {
        const errMsg: string = getErrorMessage(error, true)

        notifier.error(errMsg)
      }
    }
  })
  const enablePublicEndpoint = () => {
    return mutator.mutateAsync({
      clusterId,
      data: {
        cluster: {
          endpoints: {
            public: {
              disabled: false
            }
          }
        },
        updateMask: 'endpoints.public.disabled'
      },
      params: {
        orgId,
        projectId
      }
    })
  }

  if (!clusterQuery.isFetched || !cluster?.endpoints?.public?.disabled) {
    return null
  }

  return (
    <Alert color="red" icon={<IconXCircle size={14} />} sx={{ padding: '10px 12px' }} {...alertProps}>
      <Group gap={8} justify="space-between" align="flex-start" wrap="nowrap">
        <Box>
          This instance's public endpoint is disabled. Enable it to allow the MCP Server to access this instance.
        </Box>
        <Button
          variant="default"
          size="sm"
          loading={mutator.isLoading}
          onClick={enablePublicEndpoint}
          data-mp-event="Enable public endpoint button clicked"
          data-mp-location="Starter AI tools modal"
        >
          Enable Public Endpoint
        </Button>
      </Group>
    </Alert>
  )
})
