import { Box, Typography, Badge, Flex, Button, Modal, Anchor, Group, useComputedColorScheme } from '@tidbcloud/uikit'
import { ExpandNavbarButtonPlaceholder } from '@tidbcloud/uikit/biz'
import { IconCoins02, IconLayersThree01, IconZapFast } from '@tidbcloud/uikit/icons'
import { useEffect, useState } from 'react'

import { ReasonHoverHint } from 'dbaas/components/HoverHint/ReasonHoverHint'
import { useAccessDeniedHintReason } from 'dbaas/contexts/access-control'
import useQuery from 'dbaas/utils/useQuery'
import DataserviceEmptyDarkSVG from 'media/dataservice-empty-dark.svg?react'
import DataserviceEmptyLightSVG from 'media/dataservice-empty-light.svg?react'

import { useDataApiContext } from '../context'
import { clearCreateFormStorageDatas, useGithubAuthRequest } from '../helpers'

import CreateForm from './CreateForm'
import CreateSampleData from './CreateSampleData'

const CreateApp = () => {
  const { setIsReposConflict, setDirectoryErrInfo, createDataAppFromLogs } = useDataApiContext()
  const [opened, setOpened] = useState(false)
  const [requestId] = useGithubAuthRequest()
  const colorScheme = useComputedColorScheme()
  const isDark = colorScheme === 'dark'
  const query = useQuery()
  const createType = query.get('type')
  const accessible = useAccessDeniedHintReason({
    id: 'ProjectDataServiceGate'
  })

  useEffect(() => {
    if (createType) {
      setOpened(true)
    }
  }, [])

  useEffect(() => {
    if (createDataAppFromLogs) {
      setOpened(true)
    }
  }, [createDataAppFromLogs])

  useEffect(() => {
    if (requestId) {
      setOpened(true)
    }
  }, [requestId])

  const clear = () => {
    setOpened(false)
    clearCreateFormStorageDatas()
    setIsReposConflict(false)
    setDirectoryErrInfo('')
  }

  const descItem = ({
    title,
    desc,
    isFirst,
    isLast,
    isCenter,
    icon
  }: {
    title: string
    desc: string
    isFirst?: boolean
    isLast?: boolean
    isCenter?: boolean
    icon: any
  }) => {
    return (
      <Box
        px={24}
        py={16}
        bg="carbon.3"
        sx={(theme) => ({
          borderRadius: theme.defaultRadius,
          position: 'relative',
          flex: !isFirst && !isLast ? 2 : 3
        })}
      >
        <Box
          sx={(theme) => ({
            display: 'inline-block',
            width: 2,
            height: isCenter ? 44 : 22,
            position: 'absolute',
            top: isCenter ? -46 : -24,
            left: '50%',
            backgroundColor: theme.colors.carbon[4]
          })}
        ></Box>
        <Box
          sx={(theme) => ({
            display: 'inline-block',
            width: isFirst ? `calc(50% + 24px)` : 'auto',
            height: 2,
            position: 'absolute',
            top: -24,
            left: isFirst ? '50%' : 0,
            right: isLast ? '50%' : isCenter ? -24 : 0,
            backgroundColor: theme.colors.carbon[4]
          })}
        ></Box>

        <Flex align="center" justify="center" mb={8}>
          <Box component={icon} size={16} />
          <Typography variant="title-md" ml={16}>
            {title}
          </Typography>
        </Flex>
        <Typography variant="body-md">{desc}</Typography>
      </Box>
    )
  }

  return (
    <Box>
      <Flex direction="column">
        <Box>
          <Flex align="center" mt={16} pl={48}>
            <ExpandNavbarButtonPlaceholder />
            <Typography variant="headline-lg" fw={300} mr={8}>
              Data Service
            </Typography>
            <Badge variant="outline" size="sm" color="carbon" c="carbon.7" fw={500}>
              Preview
            </Badge>
          </Flex>

          <Flex align="center" justify="center" direction="column" mx={24}>
            <Typography variant="headline-lg" c="carbon.7" mt={24}>
              What is Data Service?
            </Typography>

            <Box maw={1140}>
              <Typography mt={16} mx={24}>
                <b>TiDB Cloud Data Service</b> is a fully managed low-code backend-as-a-service solution that simplifies
                backend application development, empowering developers to rapidly build highly scalable, secure,
                data-driven applications. Inside Data Services, your journey begins with a Data App, a container hosting
                REST Endpoints, forming the foundation of your project.
                <Anchor
                  c="peacock.7"
                  ml={4}
                  target="_blank"
                  href="https://docs.pingcap.com/tidbcloud/data-service-overview"
                >
                  Learn more
                </Anchor>
              </Typography>
            </Box>
            <Group my={24}>
              <CreateSampleData />
              <ReasonHoverHint reasons={[accessible.reason]}>
                {({ matched }) => (
                  <Button
                    data-testid="goto-create-data-app"
                    variant="default"
                    disabled={matched}
                    onClick={() => {
                      clearCreateFormStorageDatas()
                      setOpened(true)
                    }}
                    data-mp-event="DataService create data app open modal button clicked"
                    data-mp-source="source"
                  >
                    Create Data App
                  </Button>
                )}
              </ReasonHoverHint>
            </Group>
          </Flex>
        </Box>
        <Box
          p={20}
          sx={(theme) => ({
            backgroundColor: theme.colors.carbon[2],
            flex: 1
          })}
        >
          <Box maw={980} mah={204} mx="auto">
            {isDark ? (
              <DataserviceEmptyDarkSVG width="100%" height="100%" />
            ) : (
              <DataserviceEmptyLightSVG width="100%" height="100%" />
            )}
          </Box>

          <Flex gap={24} mt={50} maw={1100} mx="auto">
            {descItem({
              title: 'Faster Time-To-Market',
              desc: 'Simplified architecture for building and deploying RESTful endpoints streamlines the middle tier, accelerating development, and improving efficiency.',
              isFirst: true,
              icon: IconZapFast
            })}

            {descItem({
              title: 'Cost Effectiveness',
              desc: 'Our pay-as-you-go model ensures affordability and efficiency.',
              isCenter: true,
              icon: IconCoins02
            })}

            {descItem({
              title: 'Fully Managed',
              desc: 'Effortless, hassle-free management of database connection pooling, scalability, security and caching.',
              isLast: true,
              icon: IconLayersThree01
            })}
          </Flex>
        </Box>
      </Flex>

      <Modal
        size={800}
        centered
        trapFocus={false}
        opened={opened}
        title="Create Data App"
        closeOnClickOutside={false}
        onClose={clear}
      >
        <CreateForm onCancel={clear} />
      </Modal>
    </Box>
  )
}

export default CreateApp
