import { Box, Card, Flex, Typography } from '@tidbcloud/uikit'
import { useEffect, useState } from 'react'

import { useListDefaultDomains } from 'dbaas/services/dataservice'
import useStores from 'dbaas/stores/useStores'

import { useDataApiContext } from '../../context'

import APIKeyList from './APIKeyList'
import { Chat2Query } from './Chat2Query'
import Configuration from './Configuration'
import CustomDomain from './CustomDomain'
import DeleteApp from './DeleteApp'
import BasicSetting from './General'
import GitHub from './Github'
import LinkedCluster from './LinkedCluster'
import OpenApi from './OpenApi'

const Settings = ({ type }: { type?: string }) => {
  const [linked, setLinked] = useState(false)
  const [createApiKeyOpen, setCreateApiKeyOpen] = useState(false)
  const {
    store: { tenantData, activeProjectId }
  } = useStores()
  const { editApp, clusterDataSource } = useDataApiContext()

  const { data: defaultCustomDomains, refetch: refetchDefaultDomains } = useListDefaultDomains(
    tenantData.id,
    activeProjectId,
    editApp?.id ?? '',
    {
      query: {
        enabled: !!tenantData.id && !!activeProjectId && !!editApp?.id,
        refetchOnWindowFocus: false
      }
    }
  )

  useEffect(() => {
    refetchDefaultDomains()
  }, [clusterDataSource])

  return (
    <Box
      sx={{
        flex: 1,
        marginTop: 4,
        marginBottom: 24,
        height: '100%',
        overflowY: 'auto',
        whiteSpace: 'nowrap'
      }}
    >
      <Flex gap={24} mt={16} mb={24} align="stretch">
        <Box sx={() => ({ flex: 4 })}>
          <BasicSetting baseUrls={defaultCustomDomains?.data?.base_urls ?? [editApp?.base_url ?? '']} />
        </Box>
        <Box sx={() => ({ flex: 3 })}>
          {type === 'chat2query' ? (
            <Card pt={24} px={24} pb={6} h="100%" sx={{ display: 'flex', flexDirection: 'column' }}>
              <Typography variant="title-md">What is Chat2Query Data App ?</Typography>
              <Typography variant="body-md" sx={{ whiteSpace: 'break-spaces' }} mt={24} mb={12}>
                TiDB Cloud provides the Chat2Query API, a RESTful interface that allows you to generate and execute SQL
                statements using AI by providing instructions. Then, the API returns the query results for you.
              </Typography>
              <Typography variant="body-md" sx={{ whiteSpace: 'break-spaces' }}>
                The Chat2Query Data App first analyzes your data using the dataSummaries API, and then generates and
                executes SQL using the chat2data API. Learn more details from{' '}
                <a
                  href="https://docs.pingcap.com/tidbcloud/use-chat2query-api#get-started-with-chat2query-api"
                  target="_blank"
                  rel="noreferrer"
                >
                  here
                </a>
                .
              </Typography>
            </Card>
          ) : (
            <GitHub onChange={(linked: boolean) => setLinked(linked)} />
          )}
        </Box>
      </Flex>
      {type !== 'chat2query' && (
        <Flex gap={24} my={24} align="stretch">
          <Box sx={() => ({ flex: 4 })}>
            <Configuration linked={linked} />
          </Box>
        </Flex>
      )}

      <APIKeyList
        open={createApiKeyOpen}
        onClose={() => {
          setCreateApiKeyOpen(false)
        }}
      />

      <OpenApi />

      <LinkedCluster />
      {type === 'chat2query' && <Chat2Query />}
      {type !== 'chat2query' && (
        <CustomDomain
          defaultDomains={defaultCustomDomains?.data?.default_domain_names || []}
          defaultPath={defaultCustomDomains?.data?.default_path ?? ''}
        />
      )}
      <DeleteApp />
    </Box>
  )
}

export default Settings
