import { ActionIcon, AvatarProps, Badge, Box, Group, HoverCard, Popover, Typography } from '@tidbcloud/uikit'
import { useDisclosure } from '@tidbcloud/uikit/hooks'
import {
  IconBookOpen02,
  IconChatRobot,
  IconCheckSquareBroken,
  IconFaceSmile,
  IconFile02,
  IconInfoCircle,
  IconLifeBuoy,
  IconLinkExternal01,
  IconMagicWand02,
  IconMessageChatCircle,
  IconMonitor01,
  IconQuestion,
  IconRocket01
} from '@tidbcloud/uikit/icons'
import { mergeSxList, rgba } from '@tidbcloud/uikit/utils'
import { observer } from 'mobx-react'
import React, { useEffect, useMemo } from 'react'
import { matchPath, useLocation } from 'react-router-dom'

import config from 'config'
import { ContactUs } from 'dbaas/components/ContactUs'
import { useAccessCheck } from 'dbaas/contexts/access-control'
import { useGetTenantSupportPlan } from 'dbaas/services'
import useStores from 'dbaas/stores/useStores'
import { useWindowSize } from 'dbaas/utils/dom'
import { eventTracking } from 'dbaas/utils/tracking'

import { CHATBOT_BASE_PATH, ChatbotEntry } from '../Chatbot'
import { TutorialProvider } from '../GettingStarted/Tutorials/context'
import { PlanLevels } from '../OrgSettings/features/Support/Plans/plans'

import {
  AGENT_BASE_PATH,
  AgentHelpCenterEntry,
  AgentPanel,
  PersistentAgentPanel,
  useAgentHelpCenterAvailability
} from './Agent'
import { EntryCard, HelpCenterCard } from './CenterCard'
import { CenterRedirect, CenterRoute, CenterSwitch } from './CenterRoute'
import { DEFAULT_HELP_PATH, useHelpCenterContext } from './context'
import { DATA_SERVICE_BASE_PATH, DataServiceGuideEntry } from './DataService'
import {
  getExpandedAgentPanelBorderStyles,
  getHelpCenterDialogDimensions,
  getHelpCenterDialogWidth,
  shouldHideHelpCenterToggle
} from './layout'
import { ONBOARDINGGUIDE_PATH, OnboardingGuideGuard } from './Onboarding'
import { SQLEditorTour, SQL_EDITOR_TOUR_PATH } from './Onboarding/Tutorials'
import { RATING_BASE_PATH, RatingStarEntry } from './RatingStar'

const Links: React.FC<React.PropsWithChildren<unknown>> = observer(() => {
  const { closeDialog, setCurrentPath, dialogOpened } = useHelpCenterContext()
  const {
    store: { tenantData },
    actions: { toggleSupportVisible }
  } = useStores()
  const [contactUsOpened, contactUsHandlers] = useDisclosure(false)

  const { data: bindedPlan = { level: PlanLevels.BASIC }, refetch } = useGetTenantSupportPlan(tenantData.id, {
    query: {
      refetchOnWindowFocus: false,
      enabled: !!tenantData.id && dialogOpened
    }
  })

  const list: {
    id: string
    icon: React.ReactNode
    avatarProps: AvatarProps
    label: string | React.ReactNode
    to?: string
    external?: boolean
    onClick?: () => void
  }[] = [
    {
      id: 'guided-tour',
      icon: <IconRocket01 size={20} c="red.7" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.red[2] } })
      },
      label: 'Guided tour of SQL Editor',
      onClick() {
        setCurrentPath(SQL_EDITOR_TOUR_PATH)
        eventTracking('Guided tour of SQL Editor Clicked')
      }
    },
    {
      id: 'hands-on-labs',
      icon: <IconCheckSquareBroken size={20} c="yellow.8" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.yellow[2] } })
      },
      label: 'Self-Paced Hands-On Labs',
      external: true,
      to: 'https://labs.tidb.io/labs',
      onClick() {
        eventTracking('Self-Paced Training Clicked')
      }
    },
    {
      id: 'documentation',
      icon: <IconBookOpen02 size={20} c="peacock.7" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.peacock[2] } })
      },
      label: 'Documentation',
      external: true,
      to: 'https://docs.pingcap.com/tidbcloud/',
      onClick() {
        eventTracking('Help Documentation Clicked')
      }
    },
    {
      id: 'support-tickets',
      icon: <IconFile02 size={20} c="thyme.7" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.thyme[2] } })
      },
      label: (
        <Group gap={8}>
          Support Tickets
          <HoverCard width={400} withArrow={false} position="top">
            <HoverCard.Target>
              <IconInfoCircle size={16} sx={{ cursor: 'pointer' }} />
            </HoverCard.Target>
            <HoverCard.Dropdown>
              All users can submit billing and account requests. Technical support tickets are available with paid
              plans, offering faster, prioritized responses.
            </HoverCard.Dropdown>
          </HoverCard>
        </Group>
      ),
      external: true,
      to: bindedPlan.level === PlanLevels.BASIC ? config.CREATE_TICKET_BASIC_URL : config.CREATE_TICKET_OTHER_PLANS_URL,
      onClick() {
        eventTracking('Request Support Clicked')
      }
    },
    {
      id: 'apply-for-poc',
      icon: <IconMessageChatCircle size={20} c="purple.7" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.purple[2] } })
      },
      label: (
        <Group gap={8}>
          Apply for POC
          <HoverCard width={400} withArrow={false} position="top">
            <HoverCard.Target>
              <IconInfoCircle size={16} sx={{ cursor: 'pointer' }} />
            </HoverCard.Target>
            <HoverCard.Dropdown>
              Get started with up to 14 days free production-level verification and expert technical support.
            </HoverCard.Dropdown>
          </HoverCard>
        </Group>
      ),
      onClick() {
        contactUsHandlers.open()
        closeDialog()
        eventTracking('Contact Sales Clicked')
      }
    },
    {
      id: 'feedback',
      icon: <IconFaceSmile size={20} c="rosy.7" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.rosy[2] } })
      },
      label: 'Give Us Feedback',
      onClick() {
        eventTracking('Give us feedback Clicked')
        setCurrentPath(RATING_BASE_PATH)
      }
    },
    {
      id: 'system-status',
      icon: <IconMonitor01 size={20} c="green.8" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.green[2] } })
      },
      label: 'System Status',
      to: 'https://status.tidbcloud.com',
      external: true,
      onClick() {
        eventTracking('System Status Clicked')
      }
    },
    {
      id: 'support-options',
      icon: <IconLifeBuoy size={20} c="aqua.7" strokeWidth={1.5} />,
      avatarProps: {
        styles: (theme) => ({ placeholder: { backgroundColor: theme.colors.aqua[2] } })
      },
      label: 'Support Options',
      onClick() {
        toggleSupportVisible()
        closeDialog()
        eventTracking('View Support Plan Link Clicked')
      }
    }
  ]

  useEffect(() => {
    if (dialogOpened) {
      refetch()
    }
  }, [dialogOpened])

  return (
    <>
      <Box data-testid="help-center-entry-list" pb={28}>
        {list.map((item) => (
          <EntryCard
            key={item.id}
            title={item.label}
            avatar={item.icon}
            avatarProps={item.avatarProps}
            href={item.to}
            target={item.external ? '_blank' : undefined}
            rightSection={item.external ? <IconLinkExternal01 size={16} c="carbon.7" strokeWidth={1.5} /> : undefined}
            onClick={item.onClick}
            dataTestId="help-center-entry"
            dataEntry={item.id}
          />
        ))}
      </Box>
      {contactUsOpened && <ContactUs open={contactUsOpened} source="poc" onClose={contactUsHandlers.close} />}
    </>
  )
})

const DataServiceEntry = () => {
  const { setCurrentPath } = useHelpCenterContext()
  const location = useLocation()
  const isChat2query = !!matchPath(location.pathname, {
    path: '/project/data-service',
    exact: true
  })

  if (!isChat2query) {
    return null
  }

  return (
    <EntryCard
      title="Getting Started for Data Service"
      description="Learn Data Service step by step"
      avatar={<IconMagicWand02 size={20} strokeWidth={1.5} />}
      avatarProps={{
        color: 'red.8',
        styles: (theme) => ({
          placeholder: {
            backgroundColor: rgba(theme.colors.red[8], 0.1)
          }
        })
      }}
      onClick={() => {
        setCurrentPath(DATA_SERVICE_BASE_PATH)
        eventTracking('Getting Started for Data Service clicked')
      }}
    />
  )
}

const TiDBBotEntry = () => {
  const { setCurrentPath } = useHelpCenterContext()
  return (
    <EntryCard
      title={
        <Group gap={8}>
          Ask TiDB Bot
          <Badge variant="outline" size="sm" color="carbon" c="carbon.7" fw={500}>
            Preview
          </Badge>
        </Group>
      }
      description="Ask me anything about TiDB Cloud"
      avatar={<IconChatRobot size={20} c="violet.7" strokeWidth={1.5} />}
      avatarProps={{
        styles: (theme) => ({
          placeholder: {
            backgroundColor: theme.colors.violet[3]
          }
        })
      }}
      onClick={() => {
        eventTracking('Ask TiDB Bot')
        setCurrentPath(CHATBOT_BASE_PATH)
      }}
    />
  )
}

export const HelpCenterEntry = () => {
  const {
    store: {
      config: { enableChatBot }
    }
  } = useStores()
  const {
    currentPath,
    setCurrentPath,
    dialogOpened,
    openDialog,
    dialogHeight,
    setDialogHeight,
    agentPanelExpanded,
    closeDialog,
    dataServiceTooltipShow,
    noDataAppTooltipShow,
    setNoDataAppTooltipShow,
    rootStyles
  } = useHelpCenterContext()
  const { enabled: agentHelpCenterEnabled, resolved: agentHelpCenterAvailabilityResolved } =
    useAgentHelpCenterAvailability()

  const { height: windowHeight } = useWindowSize()
  const helpCenterControlsDialogHeight = currentPath === DEFAULT_HELP_PATH || currentPath === AGENT_BASE_PATH
  const expandedAgentPanel = currentPath === AGENT_BASE_PATH && agentPanelExpanded
  const hideHelpCenterToggle = shouldHideHelpCenterToggle(dialogOpened, expandedAgentPanel)
  const dialogDimensions = useMemo(
    () => getHelpCenterDialogDimensions(windowHeight, expandedAgentPanel),
    [expandedAgentPanel, windowHeight]
  )
  const helpCenterCardStyles = {
    flexDirection: 'column' as const,
    width: getHelpCenterDialogWidth(false),
    minHeight: dialogDimensions.minHeight,
    maxHeight: dialogDimensions.maxHeight,
    height: helpCenterControlsDialogHeight ? dialogDimensions.height : dialogHeight
  }

  useEffect(() => {
    if (helpCenterControlsDialogHeight) {
      setDialogHeight(dialogDimensions.height)
    }
  }, [dialogDimensions.height, helpCenterControlsDialogHeight, setDialogHeight])

  useEffect(() => {
    if (
      dialogOpened &&
      currentPath === AGENT_BASE_PATH &&
      agentHelpCenterAvailabilityResolved &&
      !agentHelpCenterEnabled
    ) {
      setCurrentPath(DEFAULT_HELP_PATH)
    }
  }, [agentHelpCenterAvailabilityResolved, agentHelpCenterEnabled, currentPath, dialogOpened, setCurrentPath])

  const toggleDialog = () => {
    if (dialogOpened) {
      closeDialog()
    } else {
      openDialog()
    }
  }

  const popoverOpend = useMemo(
    () => dataServiceTooltipShow || noDataAppTooltipShow,
    [dataServiceTooltipShow, noDataAppTooltipShow]
  )

  const dataserviceAccessible = useAccessCheck('ProjectDataServiceGate')

  const popoverConfig = useMemo(() => {
    if (dataserviceAccessible && dataServiceTooltipShow) {
      return {
        msg: (
          <Typography variant="body-lg">
            You can always revisit the '
            <Typography variant="title-md" sx={{ display: 'inline' }}>
              Guided Tour of Endpoints
            </Typography>
            ' here.
          </Typography>
        ),
        width: 280
      }
    } else if (dataserviceAccessible && noDataAppTooltipShow) {
      return {
        msg: <Typography variant="title-md">Looking for guidance? Dive into our tutorials here!</Typography>
      }
    }
  }, [dataServiceTooltipShow, noDataAppTooltipShow])

  return (
    <TutorialProvider>
      <Popover
        withArrow
        position="left"
        arrowPosition="side"
        width={popoverConfig?.width || undefined}
        opened={popoverOpend}
        disabled={!popoverOpend}
        onChange={() => setNoDataAppTooltipShow(false)}
      >
        <Popover.Target>
          <Box
            aria-label="Open Help Center modal"
            sx={mergeSxList([
              {
                position: 'fixed',
                right: 32,
                bottom: 32,
                // @FIXME billing table header overlap
                zIndex: 100
              },
              rootStyles
            ])}
          >
            <ActionIcon
              data-testid="help-center-toggle"
              w={40}
              h={40}
              variant="default"
              radius="xl"
              c="carbon.8"
              sx={(theme) => {
                return {
                  display: hideHelpCenterToggle ? 'none' : undefined,
                  backgroundColor: theme.colors.carbon[9],
                  ':hover': {
                    backgroundColor: theme.colors.carbon[8]
                  }
                }
              }}
              onClick={toggleDialog}
            >
              <IconQuestion size={20} c="carbon.0" />
            </ActionIcon>
            <Box
              sx={(theme) => ({
                opacity: dialogOpened ? 1 : 0,
                overflow: dialogOpened ? '' : 'hidden',
                pointerEvents: dialogOpened ? 'auto' : 'none',
                width: dialogOpened ? 'auto' : 0,
                height: dialogOpened ? 'auto' : 0,
                transition: 'opacity 0.4s ease-in-out',
                position: expandedAgentPanel ? 'fixed' : 'absolute',
                top: expandedAgentPanel ? 0 : undefined,
                bottom: expandedAgentPanel ? 0 : 56,
                right: expandedAgentPanel ? 0 : -16,
                borderRadius: expandedAgentPanel ? 0 : theme.defaultRadius
              })}
            >
              <PersistentAgentPanel enabled={agentHelpCenterEnabled}>
                <HelpCenterCard
                  shadow="md"
                  padding={24}
                  sx={() => ({
                    display: 'flex',
                    ...helpCenterCardStyles,
                    width: getHelpCenterDialogWidth(expandedAgentPanel),
                    borderRadius: expandedAgentPanel ? 0 : undefined,
                    ...getExpandedAgentPanelBorderStyles(expandedAgentPanel)
                  })}
                >
                  <AgentPanel />
                </HelpCenterCard>
              </PersistentAgentPanel>
              <HelpCenterCard
                shadow="md"
                padding={24}
                sx={() => ({
                  display: currentPath === AGENT_BASE_PATH ? 'none' : 'flex',
                  ...helpCenterCardStyles
                })}
              >
                <CenterSwitch>
                  <CenterRoute path={DEFAULT_HELP_PATH} exact>
                    <HelpCenterCard.Header />
                    <HelpCenterCard.Content>
                      <Typography
                        data-testid="help-center-heading"
                        variant="headline-lg"
                        mt={16}
                        mb={24}
                        ta="center"
                        fz={32}
                        fw={300}
                        lh="40px"
                        c="carbon.6"
                      >
                        How can we help?
                      </Typography>
                      <DataServiceEntry />
                      {enableChatBot && <TiDBBotEntry />}
                      {agentHelpCenterEnabled && <AgentHelpCenterEntry />}
                      <Links />
                    </HelpCenterCard.Content>
                  </CenterRoute>
                  <CenterRoute path={CHATBOT_BASE_PATH}>
                    <ChatbotEntry />
                  </CenterRoute>
                  <CenterRoute path={AGENT_BASE_PATH} />
                  <CenterRoute path={RATING_BASE_PATH}>
                    <RatingStarEntry />
                  </CenterRoute>
                  <CenterRoute path={DATA_SERVICE_BASE_PATH}>
                    <DataServiceGuideEntry />
                  </CenterRoute>
                  <CenterRoute path={ONBOARDINGGUIDE_PATH}>
                    <OnboardingGuideGuard />
                  </CenterRoute>
                  <CenterRoute path={SQL_EDITOR_TOUR_PATH}>
                    <SQLEditorTour />
                  </CenterRoute>
                  <CenterRedirect path="*" to={DEFAULT_HELP_PATH} />
                </CenterSwitch>
              </HelpCenterCard>
            </Box>
          </Box>
        </Popover.Target>
        <Popover.Dropdown>{popoverConfig?.msg}</Popover.Dropdown>
      </Popover>
    </TutorialProvider>
  )
}
