import { Card, Stack, useMantineTheme } from '@tidbcloud/uikit'
import { Alert, Box, Typography } from '@tidbcloud/uikit'
import { IconAnnotationAlert, IconInfoCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import React, { useMemo, useState } from 'react'

import Link from 'dbaas/components/Link'
import { HeroComponent } from 'dbaas/components/Measurement'
import { ALERT_SUBSCRIBER_TYPE_LABELS } from 'dbaas/features/AlertSubscription'
import { useListAlertSubscribers } from 'dbaas/services/clinicService'
import { EntityAlertSubscribersItem, EntityAlertSubscriberType } from 'dbaas/services/clinicService/interface'
import useStores from 'dbaas/stores/useStores'

import { CreateModal } from './CreateModal'
import { DeleteModal } from './DeleteModal'
import SubscribersTable from './SubscriberTable'

const SUBSCRIBE_TIPS: { [k: string]: JSX.Element } = {
  [EntityAlertSubscriberType.SLACK]: <>Please refer to documentation to learn how to set up.</>,
  [EntityAlertSubscriberType.ZOOM]: <>Please refer to documentation to learn how to set up.</>,
  [EntityAlertSubscriberType.FLASHDUTY]: <>Please refer to documentation to learn how to set up.</>,
  [EntityAlertSubscriberType.PAGERDUTY]: <>Please refer to documentation to learn how to set up.</>
}

const SUBSCRIBER_TYPES: { label: string; value: EntityAlertSubscriberType; tip?: JSX.Element }[] = Object.values(
  EntityAlertSubscriberType
).map((t) => ({
  label: ALERT_SUBSCRIBER_TYPE_LABELS[t],
  value: t,
  tip: SUBSCRIBE_TIPS[t]
}))

const AlertsSubscription: React.FC<
  React.PropsWithChildren<{ showAddSubscriber: boolean; closeAddSubscriber: () => void }>
> = observer(({ showAddSubscriber, closeAddSubscriber }) => {
  const { colors } = useMantineTheme()
  const {
    store: { tenantData, activeProjectId }
  } = useStores()
  const { isFetched, isLoading, refetch, data } = useListAlertSubscribers(tenantData.id, activeProjectId)
  const [selectedSubscriber, setSelectedSubscriber] = useState<EntityAlertSubscribersItem | null>(null)

  const dataByType = useMemo(() => {
    if (!data) {
      return undefined
    }
    return SUBSCRIBER_TYPES.map((t) => ({
      ...t,
      data: data.alertSubscribers?.filter((d) => d.subscriberType === t.value)
    }))
  }, [data])

  const noData = dataByType?.every((group) => !group.data?.length)

  return (
    <Stack gap="xl">
      {isFetched && <HeroComponent />}

      <Alert icon={<IconInfoCircle size={12} />} color="peacock">
        To subscribe alerts for Essential instances, please navigate to the target instance {'>>'} Settings {'>>'} Alert
        Subscription module for configuration. For more details about alerts, please refer to{' '}
        <Link
          href="https://docs.pingcap.com/tidbcloud/monitor-built-in-alerting"
          target="_blank"
          rel="noreferrer"
          eventName="Alert Subscription Documentation Link Clicked"
          eventParams={{ source: 'Alerts' }}
        >
          TiDB Cloud Built-in Alerting
        </Link>{' '}
        .
      </Alert>

      <Box>
        {noData && (
          <Stack justify="center" align="center" mih={512}>
            <IconAnnotationAlert size={48} color={colors.carbon[7]} />
            <Typography variant="title-lg" fz={18} c="carbon.7">
              Get started by adding subscriber
            </Typography>
            <Typography variant="body-lg" c="carbon.7" w={300} sx={{ textAlign: 'center' }}>
              Alert subscription is used to send system notifications to subscribers.
            </Typography>
          </Stack>
        )}
        <Stack gap="xl">
          {dataByType?.map((group) =>
            !!group.data?.length ? (
              <Card p="xl">
                <Stack>
                  <Stack gap={4}>
                    <Typography variant="title-lg">{group.label}</Typography>
                    {!!group.tip && (
                      <Typography variant="body-lg" c="carbon.7">
                        {group.tip}
                      </Typography>
                    )}
                  </Stack>
                  <SubscribersTable
                    type={group.value}
                    subscribers={group.data || []}
                    unsubscribe={setSelectedSubscriber}
                    loading={isLoading}
                  />
                </Stack>
              </Card>
            ) : (
              <></>
            )
          )}
        </Stack>
      </Box>

      <CreateModal
        opened={showAddSubscriber}
        orgId={tenantData.id}
        projectId={activeProjectId}
        onCancel={closeAddSubscriber}
        onSuccess={() => {
          closeAddSubscriber()
          refetch()
        }}
      />

      <DeleteModal
        opened={!!selectedSubscriber}
        orgId={tenantData.id}
        projectId={activeProjectId}
        subscriber={selectedSubscriber}
        onCancel={() => setSelectedSubscriber(null)}
        onDelete={() => {
          setSelectedSubscriber(null)
          refetch()
        }}
      />
    </Stack>
  )
})

export default AlertsSubscription
