import { Box, Group, Button, Flex, Select, Anchor, Typography } from '@tidbcloud/uikit'
import { CodeBlock } from '@tidbcloud/uikit/biz'
import { IconArrowLeft, IconGithub, IconUsers01, IconFile02, IconChatRobot } from '@tidbcloud/uikit/icons'
import { useState } from 'react'

import { DataApp } from 'dbaas/screens/DataService/types'
import { useGetBatchExample } from 'dbaas/services/dataservice'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

import { useHelpCenterContext } from '../context'

import { DATA_SERVICE_BASE_PATH, SAMPLE_DATA_APP_PATH } from '.'

export const SampleDataSuccess = () => {
  const { closeDialog, setCurrentPath, editAppInHelpCenter, setEditAppInHelpCenter } = useHelpCenterContext()
  const {
    store: { tenantData, activeProject }
  } = useStores()

  const [endpoint, setEndpoint] = useState('')

  const [codeExample, setCodeExample] = useState('')

  const { data: examples } = useGetBatchExample(tenantData.id, activeProject.id, editAppInHelpCenter?.id || '', {
    query: {
      enabled: !!tenantData.id && !!activeProject.id && !!editAppInHelpCenter?.id,
      refetchOnWindowFocus: false,
      onSuccess: (res) => {
        const list = res.data?.endpoint_examples || []
        const examples = (list.length && list[0].examples) || []
        if (list.length) {
          setCodeExample(examples.length ? examples[0].code || '' : '')
        }
      }
    }
  })

  return (
    <Flex direction="column" sx={{ flex: 1 }} h={0} mb={-24} mx={-24}>
      <Box sx={{ flex: 1, overflowY: 'auto' }} h={0} mt={16}>
        <Typography variant="headline-lg" mx={24}>
          Congratulations!
        </Typography>
        <Typography variant="body-lg" mt={8} mx={24}>
          Accessing an endpoint typically requires you to
          <Typography
            c="peacock.7"
            ml={4}
            component="a"
            onClick={() => {
              const newApp = { ...editAppInHelpCenter, endpoints: [] } as DataApp
              setEditAppInHelpCenter(newApp)
            }}
          >
            create an API Key
          </Typography>
          . However, for the purpose of this tutorial, we've already generated an API key for you.
        </Typography>
        <Typography variant="body-lg" my={12} mx={24}>
          Choose an endpoint you want to access
        </Typography>
        <Select
          mx={24}
          size="xs"
          mb={8}
          value={endpoint || codeExample}
          data={
            examples?.data?.endpoint_examples?.map((v) => ({
              label: v.path ?? '',
              value: v.examples?.[0].code || ''
            })) || []
          }
          onChange={(v) => v && setEndpoint(v)}
        ></Select>
        <Typography variant="body-lg" my={12} mx={24}>
          Copy and paste the following{' '}
          <a href="https://curl.se/download.html" target="_blank" rel="noreferrer">
            CURL
          </a>{' '}
          command into a terminal window to see the endpoint in action.
        </Typography>
        <Box mx={24}>
          <CodeBlock>{(endpoint || codeExample).replaceAll('\\n', '\n').replaceAll('\t', '  ')}</CodeBlock>
        </Box>
        <Box mt={8} mx={24} pb={16}>
          <Typography variant="body-lg" mt={24} mb={12}>
            Explore more advanced functionalities:
          </Typography>
          <Group gap={8}>
            <IconGithub />
            <Anchor
              href="https://docs.pingcap.com/tidbcloud/data-service-manage-github-connection"
              fz={14}
              c="gray"
              target="_blank"
            >
              GitHub integrations
            </Anchor>
          </Group>
          <Group gap={8}>
            <IconUsers01 />
            <Anchor
              href="https://docs.pingcap.com/tidbcloud/data-service-postman-integration"
              fz={14}
              c="gray"
              target="_blank"
            >
              Run in Postman
            </Anchor>
          </Group>
          <Group gap={8}>
            <IconFile02 />
            <Anchor
              href="https://docs.pingcap.com/tidbcloud/data-service-oas-with-nextjs"
              fz={14}
              c="gray"
              target="_blank"
            >
              Use OpenAPI specification with Next.js
            </Anchor>
          </Group>
          <Group gap={8}>
            <IconChatRobot />
            <Anchor href="https://docs.pingcap.com/tidbcloud/use-chat2query-api" fz={14} c="gray" target="_blank">
              Import a Chat2Query API
            </Anchor>
          </Group>
          <Typography variant="body-lg" my={24}>
            Still not found what you're looking for?
            <a href="https://docs.pingcap.com/tidbcloud/data-service-get-started" target="_blank" rel="noreferrer">
              {' '}
              Explore our Data Service offerings
            </a>{' '}
            for more information.
          </Typography>
        </Box>
      </Box>
      <Flex
        mx={24}
        justify="space-between"
        align="center"
        h={64}
        sx={(theme) => ({ borderTop: `1px solid ${theme.colors.carbon[4]}` })}
      >
        <Button
          variant="default"
          size="sm"
          px={12}
          onClick={() => {
            closeDialog()
            setCurrentPath(DATA_SERVICE_BASE_PATH)
            setEditAppInHelpCenter(null)
          }}
        >
          Exit Tutorial
        </Button>
        <Button
          variant="default"
          leftSection={<IconArrowLeft />}
          size="sm"
          px={12}
          onClick={() => {
            setCurrentPath(SAMPLE_DATA_APP_PATH)
            setEditAppInHelpCenter(null)
            eventTracking('Sample Data App Guided Tour complete')
          }}
        >
          Create Another
        </Button>
      </Flex>
    </Flex>
  )
}
