import React, { useEffect, useRef, useState } from 'react'
import { AnimatePresence, motion } from 'framer-motion'
import { Button, Tooltip } from '@heroui/react'
import { useLocalStorageState, useToggle } from 'ahooks'
import { LoginModal } from '../LoginModal'
import type { RootState } from '@/store'
import SendIcon from '@/assets/svg/send.svg?react'
import efficiencyIcon from '@/assets/efficiency-icon.png'
import { type WithAuthProps, withAuth } from '@/auth/withAuth'
import { useAppSelector } from '@/store/hook'
import { fetchToolList } from '@/api/home'

interface ChatEditorProps {
  onChange?: (value: string) => void
  onFocus?: () => void
  onSubmit?: (value: string, toolId?: string) => void
  onToolClick?: (isToolBtn: boolean, toolId?: string) => void
  placeholders: string[]
  showContentTips?: boolean
  initialValue?: string
}

const ChatEditorBase: React.FC<ChatEditorProps & WithAuthProps> = ({ checkAuth, onChange, onFocus, onSubmit, onToolClick, placeholders, showContentTips = false, initialValue = '' }) => {
  // const dispatch = useAppDispatch()
  const [content, setContent] = useState(initialValue)
  const editorRef = useRef<HTMLDivElement>(null)
  const [currentPlaceholder, setCurrentPlaceholder] = useState(0)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)
  const [isOpenLoginModal, isOpenLoginModalActions] = useToggle()
  const isAsking = useAppSelector((state: RootState) => state.chat.isAsking)
  const [toolList, setToolList] = useState<any[]>([])
  const [selectedToolId, setSelectedToolId] = useState<string | null>(null)
  const [isToolBtnActive, setIsToolBtnActive] = useState<boolean>(false)

  // 获取工具列表
  const getToolList = async () => {
    try {
      const res = await fetchToolList()
      if (res?.data) {
        setToolList(res.data)
      }
    }
    catch (error) {
      console.error('获取工具列表失败:', error)
    }
  }

  const startAnimation = () => {
    intervalRef.current = setInterval(() => {
      setCurrentPlaceholder(prev => (prev + 1) % placeholders.length)
    }, 3000)
  }
  const handleVisibilityChange = () => {
    if (document.visibilityState !== 'visible' && intervalRef.current) {
      clearInterval(intervalRef.current) // Clear the interval when the tab is not visible
      intervalRef.current = null
    }
    else if (document.visibilityState === 'visible') {
      startAnimation() // Restart the interval when the tab becomes visible
    }
  }

  const handleInput = () => {
    if (editorRef.current) {
      const newContent = editorRef.current.textContent || ''
      setContent(newContent)
      onChange?.(newContent)
    }
  }

  const handleSubmit = () => {
    if (isAsking)
      return
    if (checkAuth()) {
      if (content.trim()) {
        // 根据选择的工具或默认工具获取toolId
        let toolId: string | undefined

        if (selectedToolId) {
          // 如果选择了"提质增效"工具，使用对应的toolId
          toolId = selectedToolId
        }
        else if (toolList.length > 0) {
          // 如果没有选择工具，使用第一个工具的toolId
          toolId = toolList[0].toolId
        }
        onSubmit?.(content.trim(), toolId)
        setContent('')
        if (editorRef.current) {
          editorRef.current.textContent = ''
        }
      }
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSubmit()
    }
    else if (e.key === 'Backspace' && !content) {
      e.preventDefault() // 防止删除最后一个字符后继续删除
    }
  }
  const handleCloseLoginModal = () => {
    isOpenLoginModalActions.setLeft()
  }
  const handlePaste = (event: React.ClipboardEvent<HTMLDivElement>) => {
    event.preventDefault()
    const text = event.clipboardData.getData('text/plain')
    document.execCommand('insertText', false, text)
  }

  // 处理工具按钮点击
  const handleToolClick = () => {
    // 查找"提质增效"工具
    const efficiencyTool = toolList.find((tool: any) => tool.toolName === '提质增效')
    let currentToolId = null
    if (efficiencyTool) {
      setSelectedToolId(efficiencyTool.toolId)
      currentToolId = efficiencyTool.toolId
    }
    else {
      // 如果没有找到"提质增效"工具，使用第一个工具
      if (toolList.length > 0) {
        setSelectedToolId(toolList[0].toolId)
        currentToolId = toolList[0].toolId
      }
    }
    // 切换工具按钮状态
    const newToolBtnState = !isToolBtnActive
    setIsToolBtnActive(newToolBtnState)
    // 调用父组件的回调函数，传递切换后的状态和工具ID
    onToolClick?.(newToolBtnState, currentToolId)
  }

  useEffect(() => {
    startAnimation()
    document.addEventListener('visibilitychange', handleVisibilityChange)
    if (editorRef.current) {
      editorRef.current.style.height = 'auto'
      editorRef.current.style.height = `${editorRef.current.scrollHeight}px`
    }
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
      document.removeEventListener('visibilitychange', handleVisibilityChange)
      // console.log(isAsking, 'isAskingisAsking')
      // if (isAsking) {
      //   dispatch(setIsAsking(false))
      // }
    }
  }, [content])

  // 组件加载时获取工具列表
  useEffect(() => {
    getToolList()
  }, [])

  // 处理initialValue的变化
  useEffect(() => {
    if (initialValue && editorRef.current) {
      setContent(initialValue)
      editorRef.current.textContent = initialValue
      // 触发高度调整
      editorRef.current.style.height = 'auto'
      editorRef.current.style.height = `${editorRef.current.scrollHeight}px`
    }
  }, [initialValue])

  const [token] = useLocalStorageState<string | undefined>(
    '__TOKEN__',
    {
      defaultValue: '',
      listenStorageChange: true,
    },
  )

  return (
    <div
      className="flex items-end w-full h-auto relative mx-auto rounded-[24px] overflow-hidden transition duration-200 py-[8px] pl-[12px] pr-[12px] sm:py-[12px] sm:pl-[32px] sm:pr-[20px]"
      style={{
      background: '#FFFFFF',
      border: '1px solid #0a0a0a78',
      boxShadow: '0 8px 12px 0 rgba(235,235,235,0.30)',
      height: '102px',
    }}
    >
      <div
        ref={editorRef}
        contentEditable
        enterKeyHint="send"
        role="textbox"
        translate="no"
        className="w-full min-h-[40px] max-h-[48px] p-2  rounded overflow-y-auto outline-none"
        onInput={handleInput}
        onFocus={onFocus}
        onKeyDown={handleKeyDown}
        onPaste={handlePaste}
        suppressContentEditableWarning
        data-placeholder="输入您想问的问题吧～"
        style={{
          resize: 'none',
          maxHeight: '48px',
          marginBottom: '40px',
        }}
      >
      </div>
      <Tooltip isOpen={Boolean(token) && showContentTips && !isAsking && !content} color="foreground" content="请输入您的问题📖" placement="top-end">
        <Button className="ask-send" onPress={handleSubmit} radius="full" isDisabled={!content || isAsking} isIconOnly color="primary">
          <SendIcon />
        </Button>
      </Tooltip>
      <div className="absolute inset-0 flex items-center rounded-full pointer-events-none">
        <AnimatePresence mode="wait">
          {!content && (
            <motion.p
              initial={{
                y: 5,
                opacity: 0,
              }}
              key={`current-placeholder-${currentPlaceholder}`}
              animate={{
                y: 0,
                opacity: 1,
              }}
              exit={{
                y: -15,
                opacity: 0,
              }}
              transition={{
                duration: 0.3,
                ease: 'linear',
              }}
              className="dark:text-zinc-500 text-[14px] sm:text-[14px] font-normal text-[#3333334d] pl-4 sm:pl-12 text-left w-[calc(100%-2rem)] truncate"
            >
            </motion.p>
          )}
        </AnimatePresence>
      </div>
      <div className="absolute left-4 bottom-2 flex items-center gap-3 pointer-events-auto pl-[16px]">
          {/* <Button
            className="w-[96px] h-[32px] px-3 rounded-full bg-white border border-[#E6E8EB] shadow-none text-[#111827] text-[12px]"
            radius="full"
            variant="bordered"
            startContent={<img src={dataIcon} alt="数据助手" className="w-5 h-5" />}
          >
            数据助手
          </Button> */}
          <Button
            className={`w-[96px] h-[32px] px-3 rounded-full shadow-none text-[12px] transition-all duration-200 ${
              isToolBtnActive
                ? 'bg-[#29B6FD] border-[#29B6FD] text-white'
                : 'bg-white border border-[#E6E8EB] text-[#111827]'
            }`}
            radius="full"
            variant="bordered"
            startContent={<img src={efficiencyIcon} alt="提质增效" className="w-5 h-5" />}
            onPress={handleToolClick}
          >
            提质增效
          </Button>
      </div>
      <LoginModal onClose={handleCloseLoginModal} isOpen={isOpenLoginModal} />
    </div>
  )
}

export const ChatEditor = withAuth(ChatEditorBase)
