import { ActionIcon, Card, Divider, Flex, Grid, Typography } from '@tidbcloud/uikit'
import { useHover } from '@tidbcloud/uikit/hooks'
import { IconLifeBuoy, IconMagicWand02, IconRocket02 } from '@tidbcloud/uikit/icons'
import { useEffect, useState } from 'react'
import { Fragment } from 'react/jsx-runtime'
import { useHistory } from 'react-router-dom'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useSqlEditorStatus } from 'dbaas/features/ClusterManagement/feats'
import { CloudProviderConst } from 'dbaas/features/Project'
import { useHelpCenterContext } from 'dbaas/screens/HelpCenter/context'
import { ONBOARDINGGUIDE_PATH } from 'dbaas/screens/HelpCenter/Onboarding'
import { SQL_EDITOR_TOUR_PATH } from 'dbaas/screens/HelpCenter/Onboarding/Tutorials'
import { ONBOARDING_GUIDE_ACTION } from 'dbaas/screens/Onboarding/SurveyV2/questions'
import { eventTracking } from 'dbaas/utils/tracking'
import useQuery from 'dbaas/utils/useQuery'

import { ServerlessConnectionV2 } from '../../Connection/serverless'

interface ActionItemProps {
  title: string
  color: string
  icon: React.ReactNode
  description: string
  disabled?: boolean
  onClick?: () => void
}

const ActionItem = (item: ActionItemProps) => {
  const { hovered, ref } = useHover()
  return (
    <Flex
      gap="md"
      align="center"
      onClick={() => {
        if (item.disabled) {
          return
        }
        item.onClick?.()
      }}
      sx={{ cursor: item.disabled ? 'not-allowed' : 'pointer' }}
      ref={ref}
    >
      <ActionIcon
        aria-label={item.title}
        variant="light"
        size={44}
        disabled={item.disabled}
        color={item.color}
        sx={(theme) => ({
          backgroundColor: hovered && !item.disabled ? theme.colors[item.color]?.[4] || undefined : undefined,
          '&[data-disabled]': {
            color: item.disabled ? theme.colors.carbon[6] : undefined
          },
          '&:hover[data-disabled]': {
            backgroundColor: theme.colors[item.color]?.[3] || undefined
          }
        })}
      >
        {item.icon}
      </ActionIcon>
      <div>
        <Typography variant="title-lg" c={item.disabled ? 'carbon.6' : undefined}>
          {item.title}
        </Typography>
        <Typography variant="body-lg" c={item.disabled ? 'carbon.6' : 'carbon.7'}>
          {item.description}
        </Typography>
      </div>
    </Flex>
  )
}

export const ServerlessOnboaring = ({ cluster }: { cluster: SharedCluster }) => {
  const [opened, setOpened] = useState(false)
  const history = useHistory()
  const query = useQuery()
  const { setCurrentPath, openDialog } = useHelpCenterContext()

  const action = query.get('guideAction')

  const disabled = cluster?.computed?.creating
  const { visible: isSqleditorTourVisible } = useSqlEditorStatus(cluster)

  useEffect(() => {
    if (action === ONBOARDING_GUIDE_ACTION.OWN_DATA || action === ONBOARDING_GUIDE_ACTION.SAMPLE_DATA) {
      setCurrentPath(ONBOARDINGGUIDE_PATH)
      openDialog()
    }
    // only open the dialog when the action changes
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [action])

  const items: ActionItemProps[] = [
    {
      icon: <IconRocket02 size={20} />,
      title: 'Connect to your app',
      description: 'Enjoy immediate productivity in minutes',
      color: 'green',
      onClick() {
        eventTracking('Connect to your app Clicked', { from: 'overview' })
        setOpened(true)
      }
    },
    {
      icon: <IconLifeBuoy size={20} />,
      title: 'Import your own data',
      description:
        cluster.provider === CloudProviderConst.ALICLOUD
          ? 'Import from local, Alibaba Cloud OSS and CLI'
          : 'Import from local, Amazon S3 and CLI',
      color: 'violet',
      onClick() {
        eventTracking('Import your own data Clicked', { from: 'overview' })
        history.push(`/clusters/${cluster.id}/imports`)
      }
    }
  ]

  if (!cluster.computed.loading && isSqleditorTourVisible) {
    items.push({
      icon: <IconMagicWand02 size={20} />,
      title: 'Guided tour of SQL Editor',
      description: 'Learn how to perform vector search',
      color: 'peacock',
      onClick() {
        eventTracking('Guided tour of SQL Editor Clicked', { from: 'overview' })
        setCurrentPath(SQL_EDITOR_TOUR_PATH)
        openDialog()
      }
    })
  }

  return (
    <Card p="lg">
      <Grid grow>
        {items.map((item, index) => {
          return (
            <Fragment key={item.title}>
              <Grid.Col span={4} key={item.title} sx={{ display: 'flex', gap: 24 }}>
                {index !== 0 && <Divider orientation="vertical" h="100%" />}
                <ActionItem {...item} disabled={disabled} />
              </Grid.Col>
            </Fragment>
          )
        })}
      </Grid>
      <ServerlessConnectionV2 cluster={cluster} branchScope="all" opened={opened} onClose={() => setOpened(false)} />
    </Card>
  )
}
