import { Box, Flex, Loader } from '@tidbcloud/uikit'
import { useElementSize } from '@tidbcloud/uikit/hooks'
import { observer } from 'mobx-react'
import { useEffect, useRef, useState } from 'react'
import { useParams } from 'react-router-dom'

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

import { ChatProvider } from './context/chat-context-provider'
import { SqlEditorProvider } from './context/editor-context'
import { useSQLEditorContext } from './context/editor-context'
import Editor from './Editor'
import MessageLogs from './MessageLogs'
import SideMenu from './SideMenu'

const ContentLayout = observer(() => {
  const ref = useRef<HTMLDivElement>(null)
  const {
    store: { activeProjectId, tenantData }
  } = useStores()
  const { id: clusterId } = useParams() as { id: string }

  // audit log
  useChat2queryAuditLog(tenantData.id, activeProjectId, clusterId, {
    query: {
      enabled: !!(tenantData.id && activeProjectId && clusterId),
      refetchInterval: false,
      refetchOnWindowFocus: false
    }
  })

  return (
    <SqlEditorProvider>
      <ChatProvider>
        <Box
          ref={ref}
          h="100%"
          sx={(t) => ({
            backgroundColor: t.white
          })}
        >
          <Flex h="100%">
            <SideMenu />
            <Content />
          </Flex>
        </Box>
      </ChatProvider>
    </SqlEditorProvider>
  )
})

const Content = () => {
  const { sqlFiles } = useSQLEditorContext()
  const { ref: sqlContentRef, width, height } = useElementSize()
  const sqlRef = useRef<HTMLDivElement>(null)
  const [maxHeight, setMaxHeight] = useState(0)
  const [isRun, setIsRun] = useState(false)

  useEffect(() => {
    setMaxHeight(height)
  }, [height])

  const runningHeight = () => {
    setIsRun(true)

    setTimeout(() => {
      setIsRun(false)
    })
  }

  return (
    <Flex
      direction="column"
      sx={(t) => ({
        flex: 1,
        position: 'relative',
        height: '100%',
        overflow: 'hidden',
        backgroundColor: t.white
      })}
      ref={sqlContentRef}
    >
      {!sqlFiles.length && (
        <Flex
          sx={(t) => ({
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            justifyContent: 'center',
            alignItems: 'center',
            zIndex: 9999,
            backgroundColor: t.colors.carbon[1]
          })}
        >
          <Loader />
        </Flex>
      )}
      <>
        <Box sx={{ flex: 1 }} ref={sqlRef}>
          <Editor onRun={runningHeight} />
        </Box>
        <MessageLogs sqlRef={sqlRef} maxHeight={maxHeight} isRun={isRun} maxWidth={width} />
      </>
    </Flex>
  )
}

export default ContentLayout
