import { Breadcrumbs, Box, Progress, BoxProps, Badge, Typography } from '@tidbcloud/uikit'
import { IconCurrencyDollarCircle, IconBarChart08, IconGithub } from '@tidbcloud/uikit/icons'
import { startCase } from 'lodash-es'
import React from 'react'

import { HelpCenterCard } from 'dbaas/screens/HelpCenter/CenterCard'
import { CenterRoute, CenterSwitch, CenterRedirect, HeaderText } from 'dbaas/screens/HelpCenter/CenterRoute'
import { useHelpCenterContext } from 'dbaas/screens/HelpCenter/context'
import { eventTracking } from 'dbaas/utils/tracking'

import { useTutorialProgress } from './context'
import { Game, VectorGithub } from './Steps'
import { SP500 } from './Steps/SP500'

export const TUTORIAL_BASE_PATH = '/help/tutorials'

export interface TutorialCardProps extends BoxProps {
  name: string
  icon?: React.ReactNode
  title?: string
  description?: string
  onClick?: () => void
}

export const TutorialCard: React.FC<React.PropsWithChildren<TutorialCardProps>> = ({
  name,
  icon,
  title,
  description,
  ...rest
}) => {
  const { tutorial } = useTutorialProgress(name)
  const progress = tutorial.finished ? 100 : tutorial.progress || 0
  return (
    <Box
      sx={(theme) => ({
        border: `1px solid ${theme.colors.carbon[5]}`,
        padding: 16,
        borderRadius: theme.defaultRadius,
        cursor: 'pointer',
        ':hover': {
          borderColor: theme.colors.carbon[6]
        }
      })}
      {...rest}
    >
      <Box
        sx={(theme) => ({
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          color: theme.colors.carbon[8]
        })}
      >
        <Box sx={() => ({ display: 'flex', flex: 1, alignItems: 'center' })}>
          {icon}
          <Typography variant="title-lg" ml={8}>
            {title}
          </Typography>
        </Box>
        {tutorial.finished && (
          <Badge
            variant="outline"
            lh="18px"
            fw={600}
            px={4}
            py={2}
            sx={(theme) => ({ borderColor: theme.colors.green[4], color: theme.colors.green[6] })}
          >
            Completed
          </Badge>
        )}
      </Box>
      <Typography variant="body-lg" mt={8}>
        {description}
      </Typography>
      {!!progress && !tutorial.finished && <Progress value={progress} h={2} mt={8} />}
    </Box>
  )
}

export const VECTOR_GITHUB_PATH = `${TUTORIAL_BASE_PATH}/Vector Github`
export const VECTOR_GITHUB_NAME = 'vector_github'

export const TutorialsEntry = () => {
  const { currentPath, setCurrentPath } = useHelpCenterContext()

  const handleExit = () => {
    setCurrentPath(TUTORIAL_BASE_PATH)
  }

  const tutorials: (TutorialCardProps & { path: string; component: React.ReactElement })[] = [
    {
      icon: <IconCurrencyDollarCircle size={16} />,
      title: 'Steam Game Stats',
      description: 'Build your app that is all about data and stats of Steam games.',
      name: 'steam',
      path: `${TUTORIAL_BASE_PATH}/Steam Game Stats`,
      component: <Game name="steam" onExit={handleExit} />
    },
    {
      name: 'sp500',
      icon: <IconBarChart08 size={16} />,
      title: 'S&P 500 Analysis',
      description: 'Analyze and visualize stock and company data on all members of the S&P 500 financial index.',
      path: `${TUTORIAL_BASE_PATH}/SP 500 Analysis`,
      component: <SP500 name="sp500" onExit={handleExit} />
    },
    {
      name: 'vector_github',
      icon: <IconGithub size={16} />,
      title: 'Vector Search on Github Repos',
      description:
        'Learn how to perform efficient and powerful vector searches to find relevant Github repos quickly and accurately.',
      path: VECTOR_GITHUB_PATH,
      component: <VectorGithub name={VECTOR_GITHUB_NAME} onExit={handleExit} />
    }
  ]

  const titles = tutorials.reduce((prev, next) => {
    prev[next.path] = next.title
    return prev
  }, {})

  const steps = currentPath
    .split('/')
    .filter((item) => !!item)
    .map((item, index, array) => {
      const path = '/' + array.slice(0, index).concat(item).join('/')
      return {
        path,
        title: titles[path] ? titles[path] : startCase(item)
      }
    })

  return (
    <>
      <HelpCenterCard.Header>
        <Breadcrumbs
          styles={(theme) => ({
            separator: {
              marginLeft: 4,
              marginRight: 4,
              color: theme.colors.carbon[6]
            }
          })}
        >
          {steps.map((t, index) => (
            <HeaderText
              key={t + index.toString()}
              active={index === steps.length - 1}
              onClick={() => {
                setCurrentPath(t.path)
              }}
            >
              {t.title}
            </HeaderText>
          ))}
        </Breadcrumbs>
      </HelpCenterCard.Header>
      <CenterSwitch>
        <CenterRoute path={TUTORIAL_BASE_PATH} exact>
          <HelpCenterCard.Content>
            <Typography variant="headline-lg" mt={16}>
              Select a Tutorial Below
            </Typography>
            <Typography variant="body-lg" mt={8}>
              Utilize pre-built sample datasets tailored to your specific industry for a seamless start in exploring
              TiDB Cloud's features and capabilities.
            </Typography>
            {tutorials.map((item, index) => {
              const { path, component, ...rest } = item
              return (
                <TutorialCard
                  {...rest}
                  mt={index !== 0 ? 8 : 24}
                  key={item.title + '' + index.toString()}
                  onClick={() => {
                    setCurrentPath(item.path)
                    eventTracking(`Tutorial Card Clicked`, { name: item.name })
                  }}
                />
              )
            })}
          </HelpCenterCard.Content>
        </CenterRoute>
        {tutorials.map((item) => {
          return (
            <CenterRoute path={item.path} key={item.path} exact>
              {item.component}
            </CenterRoute>
          )
        })}
        <CenterRedirect path={`${TUTORIAL_BASE_PATH}/*`} to={TUTORIAL_BASE_PATH} />
      </CenterSwitch>
    </>
  )
}
