import { Divider, Card, Button, Box, Flex, Image, Typography } from '@tidbcloud/uikit'
import { IconLinkExternal01, IconCheckVerified02 } from '@tidbcloud/uikit/icons'
import { useHistory } from 'react-router-dom'

import { StepAction, StepProps } from '../../components/Action'
import { ClusterSelect } from '../../components/ClusterSelect'
import steamBg from '../../components/Images/steam.png'
import { LoadDataset } from '../../components/LoadDataset'
import { CodeSnippet, PasteIntoEditor } from '../../components/PasteIntoEditor'
import { useStepActions } from '../../helpers'

import Chat2queryStep from './Chat2queryStep'
import { TutorialProps } from './type'

const buildCode = (database: string) => {
  return [
    `USE ${database};
SELECT g.*
FROM game_genre gg
LEFT JOIN games g ON g.app_id = gg.app_id
WHERE gg.genre_id  = 9
ORDER BY g.estimated_owners DESC;`,
    `USE ${database};
With r AS (
    SELECT
        games.name,
        genre.genre_name,
        rank() over (partition by genre.genre_id order by games.metacritic_score desc) as ranking
    FROM game_genre gg
    LEFT JOIN genre ON genre.genre_id = gg.genre_id
    LEFT JOIN games ON games.app_id = gg.app_id
    WHERE games.metacritic_score != 0
)
SELECT *
FROM r
WHERE r.ranking <= 5;`,
    `USE ${database};
SELECT name, average_playtime_forever
FROM games
ORDER BY average_playtime_forever DESC
LIMIT 10;`,
    `DROP DATABASE IF EXISTS ${database};`
  ]
}

export const Game: React.FC<React.PropsWithChildren<TutorialProps>> = ({ onExit, name }) => {
  const {
    tutorial,
    onClusterSelect,
    onExit: handleExit,
    onFinish,
    onStepChange,
    onLoaded,
    loaded,
    disableStart,
    disableExit,
    onLoadStart,
    disableClusterSelect,
    onLoadTerminated
  } = useStepActions(name)
  const s3 = 's3://tidbcloud-samples/game-sample/'
  const arn = 'arn:aws:iam::385595570414:role/import-sample-access'
  const history = useHistory()
  const database = 'game'
  const codes = buildCode(database)
  const tables = [
    'all_audio_language',
    'category',
    'company',
    'developer',
    'game_category',
    'game_genre',
    'game_tag',
    'games',
    'genre',
    'language',
    'publisher',
    'supported_language',
    'tag'
  ]

  const steps: StepProps[] = [
    // Prepare data include select cluster and load dataset
    {
      component: (
        <div>
          <Typography variant="headline-md" mt={16}>
            Import Steam Dataset
          </Typography>
          <Typography variant="body-lg" mt={8}>
            Explore and perform analytical queries on a vast database featuring over 70,000 Steam game titles,
            experience TiDB's low latency and unlock valuable gaming insights with a sample webapp.
          </Typography>
          <Card.Section>
            <Divider my={24} />
          </Card.Section>
          <ClusterSelect
            value={tutorial.clusterId}
            clusterName={tutorial.clusterName}
            disabled={disableClusterSelect}
            onChange={onClusterSelect}
          />
          <Card.Section>
            <Divider my={24} />
          </Card.Section>
          <LoadDataset
            database={database}
            s3={s3}
            tables={tables}
            arn={arn}
            loaded={loaded}
            onLoadStart={onLoadStart}
            onLoaded={onLoaded}
            onLoadTerminated={onLoadTerminated}
            importId={tutorial.importId}
            clusterId={tutorial.clusterId || ''}
          />
        </div>
      )
    },
    // query 1
    {
      component: (
        <div>
          <Typography variant="headline-md" mt={16}>
            Get to Know the Data
          </Typography>
          <Typography variant="body-lg" mt={8}>
            Now we have data imported, let's get to know the data by running the following query. This query shows RPG
            games ranked by popularity.
          </Typography>
          <Card.Section>
            <Divider my={24} />
          </Card.Section>
          <Typography variant="action-md" c="carbon.9">
            SQL Preview
          </Typography>
          <PasteIntoEditor clusterId={tutorial.clusterId || ''} clusterName={tutorial.clusterName} value={codes[0]} />
        </div>
      )
    },
    // query 2
    {
      component: (
        <div>
          <Typography variant="headline-md" mt={16}>
            Run Real-time Analytic Queries
          </Typography>
          <Typography variant="body-lg" mt={8}>
            You can run the following analytical queries with built-in high performance analytics engine in Chat2Query.
          </Typography>
          <Card.Section>
            <Divider my={24} />
          </Card.Section>
          <CodeSnippet
            data={[
              {
                title: 'Query 1',
                description: 'Find top 5 rated games in each genre.',
                code: codes[1],
                clusterId: tutorial.clusterId || '',
                clusterName: tutorial.clusterName || ''
              },
              {
                title: 'Query 2',
                description: 'Find the top 10 time killers.',
                code: codes[2],
                clusterId: tutorial.clusterId || '',
                clusterName: tutorial.clusterName || ''
              }
            ]}
          />
        </div>
      )
    },
    {
      component: (
        <Chat2queryStep
          name={name}
          data={[
            {
              title: 'Question',
              description: 'Agree to the terms and copy the prompt below.',
              code: 'Top 10 popular games',
              clusterId: tutorial.clusterId || '',
              clusterName: tutorial.clusterName || ''
            }
          ]}
        />
      )
    },
    {
      component: (
        <div>
          <Typography variant="headline-md" mt={16}>
            Connect to the Application
          </Typography>
          <Typography variant="body-lg" mt={8}>
            Let's connect to the example web-based analytics application that visualizes Steam data for you.
          </Typography>
          <Button
            variant="outline"
            leftSection={<IconLinkExternal01 size={16} />}
            data-mp-event="Data App Steam Link Clicked"
            size="sm"
            styles={() => ({
              leftIcon: {
                marginRight: 4
              },
              root: {
                padding: '6px 12px',
                height: 32,
                marginTop: 16,
                ':hover': {
                  textDecoration: 'none'
                }
              },
              label: { fontSize: 14, lineHeight: '20px', fontWeight: 700 }
            })}
            onClick={() => {
              window.open('https://data-app-steam.vercel.app/', '_blank')
            }}
          >
            Go to Steam Stats App
          </Button>
          <Image mt={24} src={steamBg} />
        </div>
      )
    },
    // Finish all steps
    {
      component: (
        <Flex direction="column" h="100%">
          <Box
            sx={() => ({
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              alignItems: 'center',
              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-md" c="carbon.9" mt={16}>
              Congratulations!
            </Typography>
            <Typography variant="body-lg" mt={8} ta="center">
              You've successfully completed the tutorial and can continue playing with this unique dataset.
            </Typography>
            <Button
              onClick={() => {
                history.push(`/clusters/${tutorial.clusterId}/imports`)
              }}
              variant="default"
              size="sm"
              px={12}
              mt={24}
              styles={(theme) => ({
                root: {
                  backgroundColor: theme.colors.carbon[2],
                  ':hover': {
                    textDecoration: 'none'
                  }
                }
              })}
              data-mp-event="mp-importyourdata-1691461016661"
            >
              Import your data
            </Button>
          </Box>
          <Card.Section>
            <Divider />
          </Card.Section>
          <CodeSnippet
            my={24}
            withDivider={false}
            data={[
              {
                title: (
                  <Typography variant="action-md" c="carbon.9">
                    Learn how to drop dataset
                  </Typography>
                ),
                code: codes[3],
                clusterId: tutorial.clusterId || '',
                clusterName: tutorial.clusterName || ''
              }
            ]}
          />
        </Flex>
      )
    }
  ]
  return (
    <StepAction
      steps={steps}
      value={tutorial.step}
      disabledStart={disableStart}
      disabledExit={disableExit}
      onExit={() => {
        handleExit()
        onExit?.()
      }}
      onChange={(value) => {
        onStepChange(value, steps.length)
      }}
      onFinish={() => {
        onFinish()
        onExit?.()
      }}
    />
  )
}
