import { Button, Flex, Typography } from '@tidbcloud/uikit'
import { lazy, useState } from 'react'

import { ReasonHoverHint } from 'dbaas/components/HoverHint/ReasonHoverHint'
import Link from 'dbaas/components/Link'
import { useAccessDeniedHintReason } from 'dbaas/contexts/access-control'
import { useCanUseExternalSubscription } from 'dbaas/screens/Alerts/CreateModal'
import { ProjectPageShell } from 'dbaas/screens/ConsoleV2/components'
import { useGetAlertSubscriberQuota, useListAlertSubscribers } from 'dbaas/services/clinicService'
import useStores from 'dbaas/stores/useStores'

import { DedicatedOnly } from '../components/ProjectPageShell'

const Alerts = lazy(() => import('dbaas/screens/Alerts'))

const AlertsWrapper: React.FC<React.PropsWithChildren<unknown>> = () => {
  const [showAddSubscriber, setShowAddSubscriber] = useState(false)
  const {
    store: { tenantData, activeProjectId }
  } = useStores()
  const { isLoading, data } = useListAlertSubscribers(tenantData.id, activeProjectId)
  const { data: quotaData, isLoading: isQuotaLoading } = useGetAlertSubscriberQuota(tenantData.id, activeProjectId)
  const isOverQuotaLimit = (data?.totalSize || 0) >= (quotaData?.maxAlertSubscribersCount || 0)
  const isCreateDisabled = isLoading || isQuotaLoading || isOverQuotaLimit
  const canUseExternalSubscription = useCanUseExternalSubscription(tenantData.id, activeProjectId)
  const accessible = useAccessDeniedHintReason({ id: 'ProjectAlertAction' })

  return (
    <ProjectPageShell
      title={
        <Flex align="center">
          Alert Subscription
          <DedicatedOnly />
        </Flex>
      }
      headerProps={{
        rightSection: (
          <ReasonHoverHint
            reasons={[
              accessible.reason,
              {
                when: isOverQuotaLimit,
                hoverCardProps: {
                  width: 400,
                  shadow: 'md'
                },
                content: (
                  <Typography variant="body-md" c="carbon.7">
                    The number of created alert subscribers has reached the limit.
                    {canUseExternalSubscription ? (
                      <>
                        {' '}
                        If needed, please contact{' '}
                        <Link
                          href="https://docs.pingcap.com/tidbcloud/tidb-cloud-support"
                          target="_blank"
                          rel="noreferrer"
                          eventName="Technical Support Documentation Link Clicked"
                          eventParams={{ source: 'Alerts' }}
                        >
                          technical support
                        </Link>{' '}
                        to adjust the quota.
                      </>
                    ) : (
                      ''
                    )}
                  </Typography>
                )
              }
            ]}
          >
            {({ matched }) => (
              <Button
                data-mp-event="Alerts Subscription Subscribe Button Clicked"
                size="sm"
                onClick={() => setShowAddSubscriber(true)}
                disabled={isCreateDisabled || matched}
              >
                Add Subscriber
              </Button>
            )}
          </ReasonHoverHint>
        )
      }}
    >
      <Alerts showAddSubscriber={showAddSubscriber} closeAddSubscriber={() => setShowAddSubscriber(false)} />
    </ProjectPageShell>
  )
}

export default AlertsWrapper
