import { Button, Carousel, Embla, Grid, Loader, Progress } from '@tidbcloud/uikit'
import { useOs } from '@tidbcloud/uikit/hooks'
import { IconCheckCircleBroken } from '@tidbcloud/uikit/icons'
import { useEffect, useRef, useState } from 'react'
import { useHistory } from 'react-router-dom'

import { log } from 'common/log'
import useStores from 'dbaas/stores/useStores'
import Logo from 'media/logo-black.svg'

import { BackgroundMask } from '../User/Common/Background'

import { landingCardLogo1, landingCardLogo2, landingCardLogo3 } from './images'
import { useStyles } from './index.styles'

const Landing = () => {
  const {
    store: { activeProjectId, clusterList },
    actions
  } = useStores()
  const history = useHistory()
  const os = useOs()

  const [loading, setLoading] = useState(true)
  const [embla, setEmbla] = useState<Embla | null>(null)
  const emblaRef = useRef<Embla | null>(null)
  const timer = useRef<ReturnType<typeof setInterval>>()
  const timerCountRef = useRef(0)
  const [timerCount, setTimerCount] = useState(0)
  const clusterId = useRef('')
  const activeIndex = useRef(0)
  const listTimer = useRef<ReturnType<typeof setInterval>>()
  const { classes } = useStyles()

  useEffect(() => {
    clusterList.forEach((item) => {
      if (item.computed.isServerless && !item.computed.creating) {
        clusterId.current = item.id
        setLoading(false)
      }
    })
  }, [clusterList])

  useEffect(() => {
    getList()

    setTimer()

    listTimer.current = setInterval(getList, 3000)

    return () => {
      timer.current && clearInterval(timer.current)
      listTimer.current && clearInterval(listTimer.current)
    }
  }, [])

  const getList = async () => {
    try {
      await actions.fetchClusterList(activeProjectId)
    } catch (e: any) {
      log.warning('Fetch cluster list', e)
    }
  }

  const setTimer = () => {
    timer.current = setInterval(() => {
      const val = (timerCountRef.current + 1) % 301
      timerCountRef.current = val
      setTimerCount(val)

      if ((val > 1 && val % 100 === 1) || (val === 0 && activeIndex.current === 2)) {
        const index = (activeIndex.current + 1) % 3
        activeIndex.current = index
        // clearInterval(timer.current)
        emblaRef.current?.scrollTo(index)
      }
    }, 100)
  }

  const indexChange = (index: number) => {
    clearInterval(timer.current)
    activeIndex.current = index
    const val = index * 100 + 1

    timerCountRef.current = val
    setTimerCount(val)

    embla?.scrollTo(activeIndex.current)

    setTimer()
  }

  const toNext = (index: number) => {
    if (index === activeIndex.current) {
      return
    }
    // indexChange(activeIndex.current + 1)
    indexChange(index)
  }

  return (
    <div className={classes.landing}>
      <BackgroundMask />
      <div className="logo">
        <a href="/clusters">
          <img src={Logo} />
        </a>
      </div>
      <div className="clusterStatus">
        {loading ? (
          <div>
            <div className="creating">
              <Loader size="sm" />
              <span>It takes around 20 seconds to prepare your environment....</span>
            </div>
          </div>
        ) : (
          <div>
            <div className="succWrap">
              <div className="succ">
                <IconCheckCircleBroken />
                <span>Your environment is ready, enter SQL Editor now!</span>
              </div>
              <Button
                onClick={() => {
                  history.push(`/clusters/${clusterId.current}/sqleditor`)
                }}
                data-mp-event="mp-startnow-1691461012794"
              >
                Start Now
              </Button>
            </div>
          </div>
        )}
      </div>
      <div>
        <Carousel
          sx={{ maxWidth: '100%' }}
          mx="auto"
          loop
          getEmblaApi={(embla) => {
            setEmbla(embla)
            emblaRef.current = embla
          }}
          withIndicators={false}
          withControls={false}
          onSlideChange={toNext}
        >
          <Carousel.Slide>
            <div className="content">
              <Grid gutter="xs">
                <Grid.Col span={6}>
                  <div className="descTitle">
                    <div>Good-Bye Hand-Writing SQL</div>
                    <div className="subTitle">—— Experience SQL Editor in TiDB Cloud</div>
                  </div>
                  <div className="subDesc">
                    <div className="subDescItem">
                      <span className="index">1</span>
                      <span className="subContent">
                        Press {os === 'macos' ? 'Command' : 'Ctrl'} + I and ask question to your data
                      </span>
                    </div>
                    <div className="subDescItem">
                      <span className="index">2</span>
                      <span className="subContent">Click the "Accept" button to apply the AI-generated SQL</span>
                    </div>
                    <div className="subDescItem">
                      <span className="index">3</span>
                      <span className="subContent">Run the query to get the results</span>
                    </div>
                  </div>
                </Grid.Col>
                <Grid.Col span={6}>
                  <img className="descImg" src={landingCardLogo1} />
                </Grid.Col>
              </Grid>
            </div>
          </Carousel.Slide>
          <Carousel.Slide>
            <div className="content">
              <Grid gutter="xs">
                <Grid.Col span={6}>
                  <div className="descTitle">Instant Insight from Any Dataset</div>
                  <div className="subDesc">
                    <div className="subDescItem">
                      <span className="dot"></span>
                      <span className="subContent">Explore with 4 sample datasets</span>
                    </div>
                    <div className="subDescItem">
                      <span className="dot"></span>
                      <span className="subContent">Upload any dataset in CSV format</span>
                    </div>
                    <div className="subDescItem">
                      <span className="dot"></span>
                      <span className="subContent">Import dataset from S3 </span>
                    </div>
                  </div>
                </Grid.Col>
                <Grid.Col span={6}>
                  <img className="descImg" src={landingCardLogo2} />
                </Grid.Col>
              </Grid>
            </div>
          </Carousel.Slide>

          {/* third */}
          <Carousel.Slide>
            <div className="content">
              <Grid gutter="xs">
                <Grid.Col span={6}>
                  <div className="descTitle">Start Your Journey on Starter</div>
                  <div className="subDesc">
                    <div className="subDescItem">
                      <span className="dot"></span>
                      <span className="subContent">Full HTAP and Vector functionality</span>
                    </div>
                    <div className="subDescItem">
                      <span className="dot"></span>
                      <span className="subContent">Elastic scaling </span>
                    </div>
                    <div className="subDescItem">
                      <span className="dot"></span>
                      <span className="subContent">5GiB storage for free</span>
                    </div>
                  </div>
                </Grid.Col>
                <Grid.Col span={6}>
                  <img className="descImg" src={landingCardLogo3} />
                </Grid.Col>
              </Grid>
            </div>
          </Carousel.Slide>
        </Carousel>

        <div className="progress">
          <Progress onClick={() => indexChange(0)} value={timerCount <= 100 ? (timerCount / 100) * 100 : 0} />
          <Progress
            onClick={() => indexChange(1)}
            value={timerCount > 100 && timerCount <= 200 ? ((timerCount - 100) / 100) * 100 : 0}
          />
          <Progress onClick={() => indexChange(2)} value={timerCount > 200 ? ((timerCount - 200) / 100) * 100 : 0} />
        </div>
      </div>
    </div>
  )
}

export default Landing
