import { Alert, AlertProps, Box, Loader, notifier } from '@tidbcloud/uikit'
import { IconAlertTriangle, IconCheckCircle, IconXCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { Link } from 'react-router-dom'

import { isIPInRange } from 'dbaas/features/ClusterManagement/common/network'
import { useGetClientIP } from 'dbaas/services'
import { useServerlessServiceGetCluster } from 'dbaas/services/api-clients/v2023/serverless/v1beta1'
import useStores from 'dbaas/stores/useStores'

import { useAuthorizedNetworkHanlder } from '../../Network/serverless/FirewallRules/helpers'

interface FirewallRulesAlertProps {
  clusterId: string
  allowConnectHidden?: boolean
  alertProps?: AlertProps
}

export const FirewallRulesAlert = observer(
  ({ clusterId, allowConnectHidden = false, alertProps }: FirewallRulesAlertProps) => {
    const {
      store: {
        lastVisitLocation: { orgId, projectId }
      }
    } = useStores()
    const { data, isFetched } = useServerlessServiceGetCluster(clusterId, {
      view: 'BASIC',
      orgId,
      projectId
    })

    const ipQuery = useGetClientIP()
    const ipData = ipQuery.data

    const { update, isLoading } = useAuthorizedNetworkHanlder(
      { clusterId },
      {
        onError(errMsg) {
          notifier.error(errMsg)
        },
        onSuccess() {
          notifier.success(`Add current IP address successfully!`)
        }
      }
    )

    if (!isFetched || !ipQuery.isFetched) {
      return null
    }

    const networks = data?.endpoints?.public?.authorizedNetworks || []

    if (!networks.length) {
      return (
        <Alert color="red" icon={<IconXCircle size={14} />} sx={{ padding: '10px 12px' }} {...alertProps}>
          No Authorized Network rules have been configured. Your current IP address ({ipData?.ip}) is not allowed to
          connect by default.{' '}
          <Box
            component="a"
            sx={{ display: 'inline-flex', alignItems: 'center' }}
            data-mp-event="Add Current IP Address Button Clicked"
            onClick={() => {
              if (isLoading) {
                return false
              }
              update({
                networks: [
                  ...networks,
                  {
                    endIpAddress: ipData?.ip || '',
                    startIpAddress: ipData?.ip || '',
                    displayName: 'Current_client_IP_address'
                  }
                ]
              })
            }}
          >
            Click to add current IP address {isLoading && <Loader size={12} mx={4} />}
          </Box>{' '}
          or{' '}
          <Link data-mp-event="Go networking page Button Clicked" to={`/clusters/${clusterId}/networking`}>
            go to Networking page
          </Link>{' '}
          to configure your TiDB Cloud Authorized Network rules.
        </Alert>
      )
    }

    const allowConnect =
      ipData?.ip && networks.some((it) => isIPInRange(ipData?.ip, it.startIpAddress, it.endIpAddress))

    if (allowConnect) {
      return allowConnectHidden ? null : (
        <Alert color="green" icon={<IconCheckCircle size={14} />} sx={{ padding: '10px 12px' }} {...alertProps}>
          Your current IP address ({ipData?.ip}) is allowed to connect.
        </Alert>
      )
    }

    return (
      <Alert color="yellow" icon={<IconAlertTriangle size={14} />} sx={{ padding: '10px 12px' }} {...alertProps}>
        Your current client IP address ({ipData?.ip}) is not allowed to connect. Please{' '}
        <Link to={`/clusters/${clusterId}/networking`} data-mp-event="Go networking page Button Clicked">
          go to Networking page
        </Link>{' '}
        to check your TiDB Cloud Authorized Network rules.{' '}
        <a
          href="https://docs.pingcap.com/tidbcloud/configure-serverless-firewall-rules-for-public-endpoints/"
          target="_blank"
          rel="noreferrer"
          data-mp-event="Go networking Doc Button Clicked"
        >
          Learn more
        </a>
        .
      </Alert>
    )
  }
)
