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 { useSearchParams } from 'react-router-dom'
import { LoginModal } from '../LoginModal'
import type { RootState } from '@/store'
import SendIcon from '@/assets/svg/send.svg?react'
import { type WithAuthProps, withAuth } from '@/auth/withAuth'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { fetchToolList } from '@/api/home'
import { getUserRolesForApi } from '@/lib/utils'
import { clearCurrentToolId, createConversation, setCurrentToolId } from '@/store/conversationSlice'
// 使用本地 mock 工具列表常量，便于离线/联调阶段使用（已废弃，仅保留注释）
// const MOCK_TOOL_LIST = [
//   {
//     toolId: '6712395743241',
//     toolName: '提质增效',
//     toolContent: 'https://sit-wechat.guominpension.com/underwrite',
//     toolIcon: 'http://p-cf-co-1255000025.cos.bj.csyun001.ccbcos.co/tool-increase.svg',
//     toolType: '03',
//     userRole: '02',
//     showOrder: 8,
//   },
//   {
//     toolId: '6712395743240',
//     toolName: '数据助手',
//     toolContent: 'https://sit-wechat.guominpension.com/underwrite',
//     toolIcon: 'http://p-cf-co-1255000025.cos.bj.csyun001.ccbcos.co/tool-data.svg',
//     toolType: '03',
//     userRole: '01',
//     showOrder: 8,
//   },
//   {
//     toolId: 'general-mode',
//     toolName: '通用模式',
//     toolContent: 'https://sit-wechat.guominpension.com/underwrite',
//     toolIcon: 'http://p-cf-co-1255000025.cos.bj.csyun001.ccbcos.co/tool-normal.svg',
//     toolType: '01',
//     userRole: '00',
//     showOrder: 8,
//   },
// ] as const

interface ChatEditorProps {
  onChange?: (value: string) => void
  onFocus?: () => void
  onSubmit?: (value: string, toolId?: string) => void
  onToolClick?: (isToolBtn: boolean, toolId?: string, toolName?: string, shouldChangeStyle?: boolean) => void
  placeholders: string[]
  showContentTips?: boolean
  initialValue?: string
}
// onToolClick
const ChatEditorBase: React.FC<ChatEditorProps & WithAuthProps> = ({ checkAuth, onChange, onFocus, onSubmit, onToolClick, placeholders, showContentTips = false, initialValue = '' }) => {
  // const dispatch = useAppDispatch()
  const [content, setContent] = useState(initialValue)
  const dispatch = useAppDispatch()
  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>(true)
  const currentToolId = useAppSelector((state: RootState) => state.conversation.currentToolId)
  const [showToolQuestion, setShowToolQuestion] = useState<boolean>(false)
  const [sessionToolId, setSessionToolId] = useState<string | null>(null)
  const [searchParams, setSearchParams] = useSearchParams()
  const toolIdFromUrl = searchParams.get('toolId')

  // 获取工具列表
  const getToolList = async () => {
    try {
      // 调用真实接口获取工具列表
      const userRoles = getUserRolesForApi()
      const res = await fetchToolList({ userRoles })
      if (res?.data) {
        // 根据 toolId 去重，防止重复渲染
        const uniqueList = res.data.filter((tool: any, index: number, self: any[]) =>
          index === self.findIndex((t: any) => t.toolId === tool.toolId),
        )
        setToolList(uniqueList)
      }
      else {
        // 当接口无数据时，不使用本地 mock，直接置空
        setToolList([])
      }
    }
    catch (error) {
      console.error('获取工具列表失败:', error)
      // 接口异常时不再回退到本地 mock 常量
      setToolList([])
    }
  }

  // 根据 currentToolId 以及 sessionStorage 中的记录决定高亮逻辑
  useEffect(() => {
    // 场景：项目作为三方后台的子菜单时，外层可能清空了 sessionStorage，
    // 但重新打开时仍使用带有 ?toolId=xxx 的旧 URL。
    // 如果此时 Redux 和 sessionStorage 中都没有 currentToolId，则认为 URL 中的 toolId 已失效，
    // 主动移除该查询参数并强制回到「通用模式」，避免错误高亮到上一次的工具模式。
    if (!currentToolId && !sessionToolId && toolIdFromUrl) {
      const newSearchParams = new URLSearchParams(searchParams)
      newSearchParams.delete('toolId')
      setSearchParams(newSearchParams, { replace: true })
      setSelectedToolId(null)
      setIsToolBtnActive(true)
      return
    }

    // 只有当 sessionStorage 或 URL 中还能找到 toolId 时，才认为 Redux 中的 currentToolId 仍然有效
    const hasPersistentToolSource = Boolean(sessionToolId || toolIdFromUrl)

    if (currentToolId && hasPersistentToolSource) {
      setSelectedToolId(currentToolId)
      setIsToolBtnActive(false)
      return
    }

    if (sessionToolId) {
      setSelectedToolId(sessionToolId)
      setIsToolBtnActive(false)
      return
    }

    // 如果 currentToolId 和 sessionToolId 都没有值，根据路由中的 toolId 来决定
    if (toolIdFromUrl) {
      setSelectedToolId(toolIdFromUrl)
      setIsToolBtnActive(false)
    }
    else {
      setSelectedToolId(null)
      setIsToolBtnActive(true)
    }
  }, [currentToolId, sessionToolId, toolIdFromUrl, searchParams, setSearchParams])

  // 监听 sessionStorage 中的 currentToolId（历史点击时写入）来辅助高亮逻辑
  useEffect(() => {
    const syncSessionToolId = () => {
      const storedToolId = sessionStorage.getItem('currentToolId')
      setSessionToolId(storedToolId)
    }
    syncSessionToolId()
    window.addEventListener('storage', syncSessionToolId)
    return () => {
      window.removeEventListener('storage', syncSessionToolId)
    }
  }, [])

  // 当路由变化时，同步更新 sessionToolId（因为 storage 事件不会在同标签页触发）
  useEffect(() => {
    const storedToolId = sessionStorage.getItem('currentToolId')
    setSessionToolId(storedToolId)
  }, [toolIdFromUrl])

  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 {
          // 通用模式：不传递 toolId
          toolId = undefined
        }
        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 handleGeneralClick = async () => {
    if (!checkAuth())
      return
    // eslint-disable-next-line no-console
    console.log('[ChatEditor] 点击通用模式按钮')
    // 先更新 Redux，确保状态同步
    dispatch(clearCurrentToolId())
    // 立即更新本地状态，让 UI 立即响应
    setIsToolBtnActive(true)
    setSelectedToolId(null)
    sessionStorage.removeItem('showToolQuestion')
    sessionStorage.removeItem('currentToolId')
    setSessionToolId(null)
    setShowToolQuestion(false)
    // 清空路由中的 toolId 参数
    if (toolIdFromUrl) {
      const newSearchParams = new URLSearchParams(searchParams)
      newSearchParams.delete('toolId')
      setSearchParams(newSearchParams, { replace: true })
    }
    try {
      await dispatch(createConversation({
        conversationData: {},
        shouldNavigate: true,
        shouldSendQuestion: '',
      })).unwrap()
      onToolClick?.(true, undefined, '通用模式', false)
    }
    catch (error) {
      console.error('创建会话失败:', error)
    }
  }

  // 处理工具按钮点击：先创建新会话，再切换工具
  const handleToolClick = async (tool: any) => {
    if (!checkAuth())
      return
    // eslint-disable-next-line no-console
    console.log('[ChatEditor] 点击工具按钮:', {
      toolId: tool.toolId,
      toolName: tool.toolName,
    })
    if (tool.toolName === '数据助手') {
      sessionStorage.setItem('showToolQuestion', 'true')
      setShowToolQuestion(true)
    }
    else {
      sessionStorage.removeItem('showToolQuestion')
      setShowToolQuestion(false)
    }
    dispatch(setCurrentToolId(tool.toolId))
    setSelectedToolId(tool.toolId)
    setIsToolBtnActive(false)
    sessionStorage.setItem('currentToolId', tool.toolId)
    setSessionToolId(tool.toolId)
    try {
      await dispatch(createConversation({
        conversationData: { toolId: tool.toolId },
        shouldNavigate: true,
        shouldSendQuestion: '',
      })).unwrap()
      onToolClick?.(false, tool.toolId, tool.toolName, true)
    }
    catch (error) {
      console.error('创建会话失败:', error)
    }
  }

  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)
    }
  }, [content])

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

  // 监听 sessionStorage 中的 showToolQuestion
  useEffect(() => {
    const checkShowToolQuestion = () => {
      const value = sessionStorage.getItem('showToolQuestion')
      setShowToolQuestion(value === 'true')
    }
    checkShowToolQuestion()
    // 监听 storage 事件以响应其他标签页的变化
    window.addEventListener('storage', checkShowToolQuestion)
    return () => {
      window.removeEventListener('storage', checkShowToolQuestion)
    }
  }, [])

  // 处理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)',
      ...(toolList && toolList.length > 0 ? { height: '102px' } : {}),
    }}
    >
      <div
        ref={editorRef}
        contentEditable
        enterKeyHint="send"
        role="textbox"
        translate="no"
        className="w-full min-h-[40px] word-break-break-all max-h-[48px] p-2  rounded overflow-y-auto outline-none"
        onInput={handleInput}
        onFocus={onFocus}
        onKeyDown={handleKeyDown}
        onPaste={handlePaste}
        suppressContentEditableWarning
        data-placeholder={showToolQuestion ? '请输入您的问题' : '输入您想问的问题吧～'}
        style={{
          resize: 'none',
          maxHeight: '48px',
          wordBreak: 'break-all',
          ...(toolList && toolList.length > 0 ? { 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>
      {toolList && toolList.length > 0 && (
        <div className="absolute left-4 bottom-2 flex items-center gap-3 pointer-events-auto pl-[16px]">
          {toolList.map((tool: any, index: number) => {
            // 根据 selectedToolId 或路由中的 toolId 进行匹配，注意数据类型统一转换为字符串比较
            // 优先使用 selectedToolId（用户点击后的状态），其次使用 sessionStorage 中的 currentToolId（刷新时使用），再次使用路由中的 toolId（初始化时使用）
            const toolIdStr = String(tool.toolId)
            const isSelectedByState = selectedToolId && toolIdStr === String(selectedToolId)
            const isSelectedBySession = !selectedToolId && sessionToolId && toolIdStr === String(sessionToolId)
            const isSelectedByUrl = !selectedToolId && !sessionToolId && toolIdFromUrl && toolIdStr === String(toolIdFromUrl)
            // 通用模式高亮：路由内没有 toolId 或 toolId 为空时默认高亮，点击后也要高亮
            const isGeneralMode = tool.toolName === '通用模式' && isToolBtnActive && !selectedToolId && !sessionToolId && !toolIdFromUrl
            const isSelected = isSelectedByState || isSelectedBySession || isSelectedByUrl || isGeneralMode
            // 调试打印
            if (index === 0 || selectedToolId === tool.toolId) {
              // eslint-disable-next-line no-console
              console.log('[ChatEditor] 按钮渲染:', {
                toolName: tool.toolName,
                toolId: tool.toolId,
                selectedToolId,
                isSelected,
                isToolBtnActive,
              })
            }

            const baseBtnClass
              = 'w-auto h-[32px] px-3 rounded-full shadow-none text-[12px] flex items-center gap-2 transition-all duration-200 border'
            const selectedClass = isSelected
              ? ' bg-[#F3F7FF] border-[#AECBFF] text-[#165DFF]'
              : ' bg-[#FFFFFF] border-[#E6E8EB] text-[#111827]'
            const selectedVariant = isSelected ? 'solid' : 'bordered'
            const selectedColor = isSelected ? 'primary' : 'default'

            const handleButtonPress = async () => {
              // 高亮状态直接返回，避免重复触发
              if (isSelected)
                return
              if (tool.toolName === '通用模式')
                await handleGeneralClick()
              else
                await handleToolClick(tool)
            }

            // 处理后端返回的 base64 图标
            const getToolIconSrc = () => {
              if (!tool.toolIcon)
                return ''
              // 如果已经是完整的 data URL，直接返回
              if (tool.toolIcon.startsWith('data:'))
                return tool.toolIcon
              // 否则拼接为 base64 图片格式
              return `data:image/png;base64,${tool.toolIcon}`
            }

            return (
              <Button
                key={tool.toolId || `tool-${index}`}
                className={`${baseBtnClass}${selectedClass}`}
                radius="full"
                variant={selectedVariant}
                color={selectedColor}
                onPress={handleButtonPress}
              >
                {tool.toolIcon && (
                  <img
                    src={getToolIconSrc()}
                    className="w-4 h-4 flex-shrink-0"
                  />
                )}
                {tool.toolName}
              </Button>
            )
          })}
        </div>
      )}
      <LoginModal onClose={handleCloseLoginModal} isOpen={isOpenLoginModal} />
    </div>
  )
}

export const ChatEditor = withAuth(ChatEditorBase)
