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 sp500Bg from '../../components/Images/sp500.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 sector, industry, COUNT(*) AS companies
FROM companies c
WHERE c.stock_symbol IN (SELECT stock_symbol FROM index_compositions WHERE index_symbol = "SP500")
GROUP BY sector, industry
ORDER BY sector, companies DESC;`,
    `USE ${database};
SELECT
    sector,
    COUNT(*) AS companies,
    SUM(market_cap) AS total_market_cap,
    AVG(revenue_growth) AS avg_revenue_growth
FROM companies c
WHERE
    stock_symbol IN (SELECT stock_symbol FROM index_compositions WHERE index_symbol = 'SP500')
GROUP BY sector
ORDER BY avg_revenue_growth DESC;`,
    `USE ${database};
SELECT
    ic.stock_symbol,
    c.short_name,
    ic.weight,
    c.market_cap
  FROM
    \`index_compositions\` ic
    JOIN \`companies\` c ON ic.stock_symbol = c.stock_symbol
  WHERE
    ic.index_symbol = 'SP500'
  ORDER BY
    ic.weight DESC;`,
    `DROP DATABASE IF EXISTS ${database};`
  ]
}

export const SP500: React.FC<React.PropsWithChildren<TutorialProps>> = ({ onExit, name }) => {
  const {
    tutorial,
    onClusterSelect,
    onExit: handleExit,
    onFinish,
    onStepChange,
    onLoaded,
    onLoadStart,
    loaded,
    disableStart,
    disableExit,
    disableClusterSelect,
    onLoadTerminated
  } = useStepActions(name)
  const s3 = 's3://tidbcloud-samples/sp500-insight/'
  const arn = 'arn:aws:iam::385595570414:role/import-sample-access'
  const history = useHistory()
  const database = 'sp500insight'
  const codes = buildCode(database)
  const tables = [
    'companies',
    'index_compositions',
    'index_price_history',
    'indexes',
    'stock_price_history',
    'user_selected_stocks',
    'users'
  ]

  const steps: StepProps[] = [
    // Prepare data include select cluster and load dataset
    {
      component: (
        <div>
          <Typography variant="headline-md" mt={16}>
            Import S&P 500 Dataset
          </Typography>
          <Typography variant="body-lg" mt={8}>
            Execute analytical queries and create visualizations using a stock database containing millions of S&P 500
            trade records. Uncover valuable insights and trends to enhance your financial decision-making.
          </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}
            arn={arn}
            tables={tables}
            loaded={loaded}
            importId={tutorial.importId}
            onLoadStart={onLoadStart}
            onLoaded={onLoaded}
            onLoadTerminated={onLoadTerminated}
            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
            industries listed on the S&P 500.
          </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: 'Industry Sector Market Cap Comparison.',
                code: codes[1],
                clusterId: tutorial.clusterId || '',
                clusterName: tutorial.clusterName || ''
              },
              {
                title: 'Query 2',
                description: 'S&P 500 Companies by Weight.',
                code: codes[2],
                clusterId: tutorial.clusterId || '',
                clusterName: tutorial.clusterName || ''
              }
            ]}
          />
        </div>
      )
    },
    {
      component: (
        <Chat2queryStep
          name={name}
          data={[
            {
              title: 'Question',
              description: 'The company with highest revenue growth.',
              code: 'The company with highest revenue growth',
              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 application and monitor the conversion rate of these notifications. This is an example
            web based analytics application that visualizes S&P 500 stock data for you.
          </Typography>
          <Button
            variant="outline"
            leftSection={<IconLinkExternal01 size={16} />}
            data-mp-event="SP500 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://sp500insight.vercel.app/', '_blank')
            }}
          >
            Go to S&P 500 App
          </Button>
          <Image mt={24} src={sp500Bg} />
        </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-lg" 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-1691461016646"
            >
              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 || ''
              }
            ]}
          />
        </Flex>
      )
    }
  ]
  return (
    <StepAction
      steps={steps}
      value={tutorial.step}
      disabledStart={disableStart}
      disabledExit={disableExit}
      onExit={() => {
        handleExit()
        onExit?.()
      }}
      onChange={(value) => {
        onStepChange(value, steps.length)
      }}
      onFinish={() => {
        onFinish()
        onExit?.()
      }}
    />
  )
}
