import {
  Card,
  Divider,
  List,
  NavLink,
  NavLinkProps,
  Flex,
  Box,
  useMantineTheme,
  Group,
  Typography
} from '@tidbcloud/uikit'
import type { CSSObject } from '@tidbcloud/uikit/emotion'
import { useHover } from '@tidbcloud/uikit/hooks'
import { IconArrowRight, IconClock, IconFile02 } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import React, { useEffect } from 'react'
import { Link, useHistory } from 'react-router-dom'

import { HeroComponent } from 'dbaas/components/Measurement'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

import { useHelpCenterContext } from '../HelpCenter/context'

import { TUTORIAL_BASE_PATH } from './Tutorials'

interface TutorialCardProps {
  label: React.ReactNode
  content: React.ReactNode
  onClick?: () => void
  containerStyles?: CSSObject
}

export const TutorialCard: React.FC<React.PropsWithChildren<TutorialCardProps>> = ({
  label,
  content,
  onClick,
  containerStyles
}) => {
  const { hovered, ref } = useHover()
  return (
    <Flex
      ref={ref}
      direction="column"
      justify="space-between"
      sx={(theme) => {
        return {
          height: 200,
          borderRadius: theme.defaultRadius,
          borderBottomLeftRadius: 0,
          borderBottomRightRadius: 0,
          cursor: 'pointer',
          padding: 24,
          position: 'relative',
          border: `1px solid ${theme.colors.carbon[4]}`,
          borderBottom: `4px solid ${theme.colors.peacock[5]}`,
          ...(containerStyles || {})
        } as CSSObject
      }}
      onClick={onClick}
    >
      <Flex align="center" c="carbon.7">
        <IconClock size={16} />
        <Typography variant="body-lg" ml={4}>
          {label}
        </Typography>
      </Flex>
      <Box
        sx={() => ({
          fontWeight: 700,
          fontSize: 20,
          lineHeight: '30px'
        })}
      >
        {content}
        <Box
          sx={() => ({
            display: 'inline-block',
            marginLeft: hovered ? 12 : 4,
            transition: 'all ease-in-out 0.2s',
            opacity: hovered ? 1 : 0,
            '& > svg': {
              verticalAlign: 'middle'
            }
          })}
        >
          <IconArrowRight className="icon" size={20} />
        </Box>
      </Box>
    </Flex>
  )
}

interface LinkCardProps {
  title: string
  links: { to: string; external?: boolean; title: string }[]
  minWidth?: number
}

export const LinkCard: React.FC<React.PropsWithChildren<LinkCardProps>> = ({ title, links, minWidth = 220 }) => {
  const onClick = (title: string) => () => {
    eventTracking(`${title} Link Clicked`)
  }

  return (
    <div>
      <Typography variant="title-md" mb={12}>
        {title}
      </Typography>
      <List listStyleType="none" spacing={4}>
        {links.map((link, index) => {
          const Title = <Typography variant="body-lg">{link.title}</Typography>
          const navStyles: NavLinkProps['styles'] = (theme) => ({
            icon: {
              alignSelf: 'flex-start',
              marginTop: 2,
              marginRight: 8
            },
            root: {
              minWidth,
              padding: 4,
              borderRadius: theme.defaultRadius,
              ':hover': {
                textDecoration: 'none'
              }
            }
          })
          return (
            <List.Item key={link.title + index.toString()}>
              {link.external ? (
                <NavLink
                  leftSection={<IconFile02 size={16} />}
                  component="a"
                  href={link.to}
                  target="_blank"
                  rel="noreferrer"
                  label={Title}
                  onClick={onClick(link.title)}
                  styles={navStyles}
                />
              ) : (
                <NavLink
                  leftSection={<IconFile02 size={16} />}
                  component={Link}
                  to={link.to}
                  label={Title}
                  onClick={onClick(link.title)}
                  styles={navStyles}
                />
              )}
            </List.Item>
          )
        })}
      </List>
    </div>
  )
}

export const GettingStarted = observer(() => {
  const {
    actions: { fetchClusterList },
    store: { clusterList }
  } = useStores()

  const history = useHistory()
  const { currentPath, setCurrentPath, openDialog } = useHelpCenterContext()
  const theme = useMantineTheme()

  const activeCluster = clusterList.find((cluster) => {
    return cluster.computed.isServerless && !cluster.computed.creating
  })

  const tutorials: TutorialCardProps[] = [
    {
      label: '3 mins',
      content: (
        <>
          Query
          <br />
          Sample Dataset
        </>
      ),
      onClick: () => {
        if (!currentPath.startsWith(TUTORIAL_BASE_PATH)) {
          setCurrentPath(TUTORIAL_BASE_PATH)
        }
        openDialog()
      }
    },
    {
      label: '10 mins',
      content: (
        <>
          Import
          <br />
          Your Data
        </>
      ),
      onClick: () => {
        if (activeCluster) {
          return history.push(`/clusters/${activeCluster.id}/imports`)
        }
        history.push('/clusters/create-cluster')
      },
      containerStyles: {
        borderBottomColor: theme.colors.purple[5]
      }
    },
    {
      label: '15 mins',
      content: (
        <>
          Explore
          <br />
          Developer Hub
        </>
      ),
      onClick: () => {
        window.open('https://www.pingcap.com/developers/', '_target')
      },
      containerStyles: {
        borderBottomColor: theme.colors.blue[5]
      }
    }
  ]
  const links: LinkCardProps[] = [
    {
      title: 'TiDB Deep Dive',
      minWidth: 320,
      links: [
        {
          title: 'Harnessing the power of HTAP databases',
          to: 'https://www.pingcap.com/blog/harnessing-the-power-of-htap-databases/',
          external: true
        },
        {
          title: 'Real-World HTAP architectures',
          to: 'https://www.pingcap.com/blog/real-world-htap-a-look-at-tidb-and-singlestore-and-their-architectures/',
          external: true
        },
        {
          title: 'Forrester WAVE: TiDB is a strong performer',
          to: 'https://www.pingcap.com/press-release/pingcap-named-a-strong-performer-among-translytical-data-platforms-by-independent-research-firm/',
          external: true
        },
        {
          title: 'Become a certified TiDB expert',
          to: 'https://www.pingcap.com/education/',
          external: true
        }
      ]
    },
    {
      title: 'Customer Cases',
      minWidth: 280,
      links: [
        {
          title: 'Pinterest: From HBase to TiDB',
          to: 'https://medium.com/pinterest-engineering/online-data-migration-from-hbase-to-tidb-with-zero-downtime-43f0fb474b84',
          external: true
        },
        {
          title: 'CAPCOM: Why we chose TiDB',
          to: 'https://www.pingcap.com/case-study/why-capcom-chose-tidb-cloud-as-its-scalable-managed-database-for-online-game/',
          external: true
        },
        {
          title: 'NFTSCan: Web3 business with HTAP',
          to: 'https://www.pingcap.com/case-study/empower-web3-business-with-a-scalable-htap-database-for-hybrid-workloads/',
          external: true
        },
        {
          title: 'More featured customer stories',
          to: 'https://www.pingcap.com/customers/',
          external: true
        }
      ]
    },
    {
      title: 'Product Resources',
      links: [
        {
          title: 'TiDB Cloud Updates',
          to: 'https://docs.pingcap.com/tidbcloud/tidb-cloud-release-notes',
          external: true
        },
        {
          title: 'TiDB Kernel Updates',
          to: 'https://docs.pingcap.com/releases/tidb-self-managed/',
          external: true
        },
        {
          title: 'Join TiDB Community',
          to: 'https://www.pingcap.com/community/',
          external: true
        },
        {
          title: 'Attend TiDB Meetups',
          to: 'https://www.pingcap.com/event/',
          external: true
        }
      ]
    }
  ]

  useEffect(() => {
    fetchClusterList()
  }, [])

  return (
    <Card p={0} withBorder>
      <HeroComponent />
      <Box p={24} pb={0}>
        <Typography variant="headline-sm" mb={4}>
          Getting Started Tutorials
        </Typography>
        <Typography variant="body-lg">Learn TiDB Cloud with hands-on tutorials.</Typography>
        <Group gap={16} mt={16} justify="space-between" grow>
          {tutorials.map((it, index) => {
            return <TutorialCard key={index.toString()} {...it} />
          })}
        </Group>
      </Box>
      <Divider my={24}></Divider>
      <Flex
        sx={() => ({
          padding: 24,
          paddingTop: 0,
          '& > div': {
            flex: 1,
            '&:not(:first-of-type)': {
              marginLeft: 16
            }
          }
        })}
      >
        {links.map((link, key) => {
          return <LinkCard key={key.toString + link.title} {...link} />
        })}
      </Flex>
    </Card>
  )
})

export default GettingStarted
