import { Box, Center, Flex, Loader, Typography } from '@tidbcloud/uikit'
import { IconCheckVerified02, IconLifeBuoy, IconRocket02 } from '@tidbcloud/uikit/icons'
import { useMount } from 'ahooks'
import { observer } from 'mobx-react'
import { useMemo, useRef, useState } from 'react'
import { useHistory } from 'react-router-dom'

import { ServerlessConnectionV2 } from 'dbaas/screens/ClusterV2/features/Connection/serverless'
import { useStepActions } from 'dbaas/screens/GettingStarted/helpers'
import { getTutorialKey, TutorialItem } from 'dbaas/screens/GettingStarted/Tutorials/context'
import { ONBOARDING_GUIDE_ACTION } from 'dbaas/screens/Onboarding/SurveyV2/questions'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

import { EntryCard, HelpCenterCard } from '../CenterCard'
import { CenterBreadcrumbs } from '../CenterRoute'
import { DEFAULT_HELP_PATH, useHelpCenterContext } from '../context'

import { ImportSampleData } from './ImportSampleData'
import { SQL_EDITOR_TOUR_NAME, SQL_EDITOR_TOUR_PATH } from './Tutorials'

export const ONBOARDINGGUIDE_PATH = '/help/Guide'

export const OnboardingGuide = observer(() => {
  const {
    store: { currentCluster, tenantData, lastVisitLocation, userProfile }
  } = useStores()
  const [opened, setOpened] = useState(false)
  const history = useHistory()
  const query = useMemo(() => new URLSearchParams(window.location.search), [])
  const { setCurrentPath } = useHelpCenterContext()
  const ref = useRef<{
    import: () => Promise<void>
  }>(null)

  const action = query.get('guideAction')
  const targetId = query.get('targetId') || ''

  const s3 = 's3://tidbcloud-samples/github-sample/'
  const arn = 'arn:aws:iam::385595570414:role/import-sample-access'
  const database = 'github_sample'
  const name = SQL_EDITOR_TOUR_NAME
  const { tutorial, update, loaded, onLoadTerminated } = useStepActions(name)

  useMount(() => {
    if (action !== ONBOARDING_GUIDE_ACTION.SAMPLE_DATA) {
      return
    }
    let value: TutorialItem = {
      step: 0
    }
    try {
      const key = JSON.parse(
        localStorage.getItem(getTutorialKey(userProfile.id, tenantData.id, lastVisitLocation.projectId)) || '{}'
      ) as Record<string, TutorialItem>
      value = key[name] || {}
    } catch (_e) {}
    if (targetId && targetId !== value.loadedClusterId && !value.importId) {
      ref.current?.import()
    }
  })

  return (
    <Flex direction="column" h="100%">
      <HelpCenterCard.Header>
        <CenterBreadcrumbs items={[{ path: DEFAULT_HELP_PATH, title: 'Help' }]} />
      </HelpCenterCard.Header>
      <Flex direction="column" justify="center" align="center" sx={{ flex: 1 }}>
        <Box
          sx={(theme) => ({
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            color: theme.colors.green[7],
            backgroundColor: theme.colors.green[1],
            width: 48,
            height: 48,
            borderRadius: '100%'
          })}
        >
          <IconCheckVerified02 size={20} />
        </Box>
        <Typography variant="headline-lg" c="carbon.9" mt={16}>
          Congratulations!
        </Typography>
        {action === ONBOARDING_GUIDE_ACTION.SAMPLE_DATA ? (
          <>
            <Typography variant="body-lg" ta="center" maw={320} mt="md">
              You have successfully set up your first cluster. Once your data is ready, feel free to check out the{' '}
              <a
                onClick={(e) => {
                  e.preventDefault()
                  eventTracking('Guided tours of SQL Editor Clicked', { from: 'help-center' })
                  setCurrentPath(SQL_EDITOR_TOUR_PATH)
                }}
              >
                Guided tours of SQL Editor
              </a>
              .
            </Typography>
            {targetId && (
              <ImportSampleData
                ref={ref}
                orgId={tenantData.id}
                projectId={lastVisitLocation.projectId}
                database={database}
                s3={s3}
                tables={[]}
                arn={arn}
                loaded={loaded}
                onLoadStart={(id) => {
                  update({ importId: id, clusterId: targetId, clusterName: '' })
                }}
                onLoaded={() => {
                  update({
                    importId: tutorial.importId,
                    clusterId: targetId,
                    loadedClusterId: targetId,
                    clusterName: '',
                    step: 1,
                    progress: Math.floor((1 / 5) * 100)
                  })
                }}
                onLoadTerminated={onLoadTerminated}
                importId={tutorial.importId}
                clusterId={targetId || ''}
              />
            )}
          </>
        ) : (
          <>
            <Typography variant="body-lg" ta="center" mt={8} mb={48}>
              You have successfully set up your first cluster.
            </Typography>
            <EntryCard
              title="Connect to your app"
              description="Enjoy immediate productivity in minutes"
              avatar={<IconRocket02 size={20} />}
              onClick={() => {
                setOpened(true)
                eventTracking('Connect to your app Clicked', { from: 'help-center' })
              }}
              avatarProps={{
                color: 'green',
                styles: (theme) => ({
                  placeholder: {
                    backgroundColor: theme.colors.green[2]
                  }
                })
              }}
            />
            <EntryCard
              title="Import your down data"
              description="Import from local, Amazon S3, and CLI tools"
              avatar={<IconLifeBuoy size={20} />}
              onClick={() => {
                eventTracking('Import your down data Clicked', { from: 'help-center' })
                history.push(`/clusters/${currentCluster?.id}/imports`)
              }}
              avatarProps={{
                color: 'violet',
                styles: (theme) => ({
                  placeholder: {
                    backgroundColor: theme.colors.violet[2]
                  }
                })
              }}
            />
          </>
        )}
      </Flex>
      {!!currentCluster && (
        <ServerlessConnectionV2
          cluster={currentCluster}
          branchScope="all"
          opened={opened}
          onClose={() => setOpened(false)}
        />
      )}
    </Flex>
  )
})

export const OnboardingGuideGuard = observer(() => {
  const {
    store: { userProfile, tenantData, lastVisitLocation }
  } = useStores()
  if (!userProfile.id || !tenantData.id || !lastVisitLocation.projectId) {
    return (
      <Center h="100%">
        <Loader size={24} />
      </Center>
    )
  }
  return <OnboardingGuide />
})
