import { Box, Loader, Flex, Typography, ActionIcon, Button } from '@tidbcloud/uikit'
import { IconCheckCircle, IconXCircle, IconInfoCircle, IconStars02 } from '@tidbcloud/uikit/icons'
import DOMPurify from 'dompurify'
import { useEffect, useState } from 'react'

import { useSQLEditorContext } from '../context/editor-context'
import { getEditor } from '../sql-code-editor/editor-cache'
import { activePromptInput, isPromptInputActive } from '../sql-code-editor/extensions/ai-assistant'
import { SqlRes } from '../types'

export const RunningTips = () => {
  return (
    <Flex direction="column">
      <Flex align="center">
        <Loader size={20} mr={8} />
        <Typography variant="headline-sm" fw={500} c="carbon.7">
          Query Running
        </Typography>
      </Flex>
      <Typography variant="label-lg" c="carbon.7" mt={8}>
        The execution result is loading
      </Typography>
    </Flex>
  )
}

export const RunSuccTips: React.FC<React.PropsWithChildren<{ message: string | undefined; hideTitle?: boolean }>> = ({
  message = '',
  hideTitle
}) => {
  return (
    <Flex direction="column">
      {!hideTitle && (
        <Flex align="center">
          <ActionIcon c="green.8" variant="transparent" size={20} sx={{ cursor: 'default' }}>
            <IconCheckCircle size={20} strokeWidth={2} />
          </ActionIcon>
          <Typography variant="headline-sm" fw={500} c="green.8" ml={8}>
            Query OK.
          </Typography>
        </Flex>
      )}
      <Typography variant="body-lg" c="carbon.8" my={8}>
        {message}
      </Typography>
    </Flex>
  )
}

export const RunErrTips: React.FC<React.PropsWithChildren<{ data: SqlRes }>> = ({ data }) => {
  const { editedSqlFile } = useSQLEditorContext()
  const [message, setMessage] = useState(data.res ?? '')
  const fixMsg =
    'The original SQL statement has been changed. Please rerun it before attempting to use the Fix feature again.'
  const activeMsg = 'Prompt input dialog is active. Please close it first.'

  useEffect(() => {
    setMessage(data.res ?? '')
  }, [data.res])

  // TODO: move a better place
  function fixByChat2Query() {
    if (data.fileId !== editedSqlFile.id) return

    const activeEditor = getEditor(data.fileId + '')
    if (!activeEditor) return

    if (isPromptInputActive(activeEditor.editor.state)) {
      setMessage(activeMsg)
      return
    }

    const { from, to, content } = data.statement

    if (content && activeEditor.editor.state.doc.sliceString(from, to).trim() !== content) {
      setMessage(fixMsg)
      return
    }

    setMessage(data.res ?? '')
    activePromptInput(
      activeEditor.editor,
      'Fix code error',
      true,
      {
        from,
        to
      },
      { sql_error: data.res ?? '' }
    )
  }

  return (
    <Box>
      <Flex direction="column">
        <Flex align="center">
          <ActionIcon c="red.8" variant="transparent" size={20} sx={{ cursor: 'default' }}>
            <IconXCircle size={20} />
          </ActionIcon>
          <Typography variant="headline-sm" fw={500} c="red.8" ml={8}>
            {message !== fixMsg && message !== activeMsg && 'Query'} Failed.
          </Typography>
        </Flex>
        <Typography variant="body-lg" c="carbon.8" my={8}>
          {typeof message === 'string' ? <span>{DOMPurify.sanitize(message)}</span> : <>{message as any}</>}
        </Typography>
      </Flex>

      <Button mt={8} size="sm" data-mp-event="Fix by Chat2query button clicked" onClick={fixByChat2Query}>
        <IconStars02 />
        <Box ml={4}>Fix by Chat2Query</Box>
      </Button>
    </Box>
  )
}

export const RunWarningTips: React.FC<React.PropsWithChildren<{ message: string[] | undefined }>> = ({
  message = []
}) => {
  return (
    <Flex direction="column">
      <Flex align="center">
        <ActionIcon c="yellow.8" variant="transparent" size={20} sx={{ cursor: 'default' }}>
          <IconInfoCircle size={20} />
        </ActionIcon>
        <Typography variant="headline-sm" fw={500} c="yellow.8" ml={8}>
          Query Warning.
        </Typography>
      </Flex>
      <Box sx={{ textAlign: 'center' }}>
        {(message || []).map((item) => (
          <Typography variant="body-lg" my={8} ta="left" c="carbon.8">
            {item}
          </Typography>
        ))}
      </Box>
    </Flex>
  )
}
export default RunningTips
