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 { useLocation, useNavigate, 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 { clearBusinessInsightWorkflow, clearCurrentToolId, fetchConversations, setCurrentToolId } from '@/store/conversationSlice'
import { setIsAsking } from '@/store/chatSlice'
import { fetchToolList } from '@/api/home'
import { safeSessionStorageGetItem, safeSessionStorageRemoveItem, safeSessionStorageSetItem } from '@/lib/utils'
import { clearWorkflowToolCaches } from '@/lib/workflowToolParams'
import type { ToolListRow } from '@/types/toolList'
import { getToolQuestionPairFromRow, isGeneralInstitutionalToolRow, normalizeToolId } from '@/lib/toolRoleRecordTypes'
import { fetchSessionConversationId, fetchUserQaRecordPage } from '@/api/conversation'
import { hasQaWorkflowContext } from '@/pages/Chat/helper'

interface ChatEditorProps {
  onChange?: (value: string) => void
  onFocus?: () => void
  onSubmit?: (value: string, toolId?: string) => void
  onToolClick?: (isToolBtn: boolean, toolId?: string, toolName?: string, shouldChangeStyle?: boolean, conversationId?: string, isLoading?: boolean, toolMeta?: Pick<ToolListRow, 'commonQuestionApi' | 'businessInsightConfigTypes' | 'showStructuredQueryPlaceholder'>) => void
  placeholders: string[]
  showContentTips?: boolean
  initialValue?: string
  hideTools?: boolean // 隐藏工具选择部分
  /** 工作流表单展示且未提交时禁用底部输入 */
  inputDisabled?: boolean
}
// onToolClick
const ChatEditorBase: React.FC<ChatEditorProps & WithAuthProps> = ({ checkAuth, onChange, onFocus, onSubmit, onToolClick, placeholders, showContentTips = false, initialValue = '', hideTools = false, inputDisabled = false }) => {
  // 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<ToolListRow[]>([])
  const [selectedToolId, setSelectedToolId] = useState<string | null>(null)
  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 location = useLocation()
  const navigate = useNavigate()
  const toolIdFromUrl = searchParams.get('toolId')
  const fromCollect = location.state?.fromCollect

  /** 等待 token 就绪，确保登录接口返回后才继续 */
  const waitForToken = async (maxWaitTime = 3000): Promise<boolean> => {
    const startTime = Date.now()
    let initialToken = ''
    // 先获取初始 token 值
    try {
      const initialTokenStr = window.localStorage.getItem('__TOKEN__') || '""'
      initialToken = JSON.parse(initialTokenStr) || ''
    }
    catch {
      initialToken = ''
    }

    // 如果初始没有 token，等待 token 出现（从无到有，说明登录完成）
    if (!initialToken) {
      while (Date.now() - startTime < maxWaitTime) {
        const tokenStr = window.localStorage.getItem('__TOKEN__') || '""'
        let token = ''
        try {
          token = JSON.parse(tokenStr) || ''
        }
        catch {
          token = ''
        }
        if (token) {
          // token 从无到有，说明登录完成，再等待一小段时间确保写入完成
          await new Promise(resolve => setTimeout(resolve, 200))
          return true
        }
        // 等待 100ms 后再次检查
        await new Promise(resolve => setTimeout(resolve, 100))
      }
      return false
    }

    // 如果初始有 token，可能是旧 token 或新 token
    // 等待一小段时间，确保登录流程有足够时间完成（登录接口可能会更新 token）
    // 同时监听 token 变化
    let tokenChanged = false
    const checkTokenChange = () => {
      try {
        const currentTokenStr = window.localStorage.getItem('__TOKEN__') || '""'
        const currentToken = JSON.parse(currentTokenStr) || ''
        if (currentToken && currentToken !== initialToken) {
          tokenChanged = true
        }
      }
      catch {
        // 忽略解析错误
      }
    }

    // 监听 storage 事件（跨标签页）
    window.addEventListener('storage', checkTokenChange)
    // 轮询检查（同标签页）
    const interval = window.setInterval(() => {
      checkTokenChange()
    }, 100)

    // 等待最多 1 秒，检测 token 是否变化
    const waitForChange = new Promise<void>((resolve) => {
      setTimeout(() => {
        window.removeEventListener('storage', checkTokenChange)
        clearInterval(interval)
        resolve()
      }, 1000)
    })
    await waitForChange

    // 如果 token 变化了，说明登录完成，再等待一小段时间确保写入完成
    if (tokenChanged) {
      await new Promise(resolve => setTimeout(resolve, 200))
      return true
    }

    // 如果 token 没有变化，可能是已经登录完成，但为了确保登录流程完成，再等待一小段时间
    await new Promise(resolve => setTimeout(resolve, 300))
    return true
  }

  // 获取工具列表
  const getToolList = async () => {
    try {
      // 等待 token 就绪后再调用接口
      await waitForToken()
      // 检查缓存（有效期 5 分钟）
      const cacheKey = 'toolList'
      const cached = sessionStorage.getItem(cacheKey)
      if (cached) {
        try {
          const { toolList, timestamp } = JSON.parse(cached) as { toolList: ToolListRow[], timestamp: number }
          if (Date.now() - timestamp < 5 * 60 * 1000) {
            setToolList(toolList)
            return
          }
        }
        catch {
          // 缓存解析失败，继续调用接口
        }
      }
      // 调用真实 API 获取工具列表
      const res = await fetchToolList()
      if (res?.data && Array.isArray(res.data) && res.data.length > 0) {
        const rows = res.data as ToolListRow[]
        setToolList(rows)
        sessionStorage.setItem(cacheKey, JSON.stringify({
          toolList: rows,
          timestamp: Date.now(),
        }))
      }
    }
    catch (error) {
      console.error('获取工具列表失败:', error)
    }
  }

  // 根据 currentToolId 以及 sessionStorage 中的记录决定高亮逻辑
  useEffect(() => {
    if (currentToolId && !sessionToolId && !fromCollect) {
      // 清除过期的 Redux 值
      dispatch(clearCurrentToolId())
      // 如果 URL 中还有 toolId，也清除它
      if (toolIdFromUrl) {
        const newSearchParams = new URLSearchParams(searchParams)
        newSearchParams.delete('toolId')
        setSearchParams(newSearchParams, { replace: true })
      }
      setSelectedToolId(toolList.length > 0 ? normalizeToolId(toolList[0].toolId) : null)
      return
    }

    if (!currentToolId && !sessionToolId && toolIdFromUrl) {
      const newSearchParams = new URLSearchParams(searchParams)
      newSearchParams.delete('toolId')
      setSearchParams(newSearchParams, { replace: true })
      setSelectedToolId(toolList.length > 0 ? normalizeToolId(toolList[0].toolId) : null)
      return
    }

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

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

    if (sessionToolId) {
      setSelectedToolId(sessionToolId)
      return
    }

    // 如果 currentToolId 和 sessionToolId 都没有值，根据路由中的 toolId 来决定
    if (toolIdFromUrl) {
      setSelectedToolId(toolIdFromUrl)
    }
    else {
      setSelectedToolId(toolList.length > 0 ? normalizeToolId(toolList[0].toolId) : null)
    }
  }, [currentToolId, sessionToolId, toolIdFromUrl, searchParams, setSearchParams, fromCollect, toolList])

  // 监听 sessionStorage 中的 currentToolId（历史点击时写入）来辅助高亮逻辑
  useEffect(() => {
    const syncSessionToolId = () => {
      const storedToolId = safeSessionStorageGetItem('currentToolId')
      setSessionToolId(storedToolId && storedToolId.trim() ? storedToolId : null)
    }
    syncSessionToolId()
    window.addEventListener('storage', syncSessionToolId)

    const handleForceReset = () => {
      syncSessionToolId()
      if (currentToolId) {
        dispatch(clearCurrentToolId())
      }
      setSelectedToolId(toolList.length > 0 ? normalizeToolId(toolList[0].toolId) : null)
    }
    window.addEventListener('forceResetToGeneralMode', handleForceReset)

    return () => {
      window.removeEventListener('storage', syncSessionToolId)
      window.removeEventListener('forceResetToGeneralMode', handleForceReset)
    }
  }, [currentToolId, dispatch, toolList])

  // 当路由变化时，同步更新 sessionToolId（因为 storage 事件不会在同标签页触发）
  useEffect(() => {
    const storedToolId = safeSessionStorageGetItem('currentToolId')
    setSessionToolId(storedToolId && storedToolId.trim() ? storedToolId : null)
    // 当路由切换（如点击历史记录）时，同步最新的 sessionStorage，避免同标签页删除后状态不同步
  }, [toolIdFromUrl, location.pathname])

  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 editorLocked = isAsking || inputDisabled

  const handleSubmit = () => {
    if (editorLocked)
      return
    // 以 DOM 为准，避免 content 状态与 contentEditable 不同步（如 IME、快速连点）导致误判为空
    const textFromDom = (editorRef.current?.textContent ?? '').trim()
    const text = textFromDom || content.trim()
    if (checkAuth()) {
      if (text) {
        const defaultToolId = toolList.length > 0 ? normalizeToolId(toolList[0].toolId) : null
        const activeToolId = selectedToolId ?? sessionToolId ?? toolIdFromUrl ?? defaultToolId
        const toolId = activeToolId || undefined
        onSubmit?.(text, 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 pickToolMeta = (t: ToolListRow) => ({
    commonQuestionApi: t.commonQuestionApi ?? undefined,
    businessInsightConfigTypes: t.businessInsightConfigTypes ?? undefined,
    showStructuredQueryPlaceholder: t.showStructuredQueryPlaceholder ?? undefined,
  })

  /** 底部工具条：统一「清缓存 → 建会话 → 换路由 → 拉 QA → 通知上层」；仅会话参数与后续是否自动 workflow 随是否通用行变化 */
  const handleWorkflowToolButtonPress = async (tool: ToolListRow) => {
    if (!checkAuth())
      return

    clearWorkflowToolCaches()
    dispatch(clearBusinessInsightWorkflow())

    const isGeneral = isGeneralInstitutionalToolRow(tool)
    const normalizedToolId = normalizeToolId(tool.toolId)
    const busiIdForSession = isGeneral ? '' : normalizedToolId
    const displayName = tool.toolName?.trim() || ''
    const parentIsToolBtn = isGeneral
    const eventToolId = isGeneral ? undefined : normalizedToolId
    const shouldChangeStyleForParent = !isGeneral

    onToolClick?.(
      parentIsToolBtn,
      eventToolId,
      displayName,
      shouldChangeStyleForParent,
      undefined,
      true,
      pickToolMeta(tool),
    )

    try {
      dispatch(setIsAsking(false))

      if (isGeneral) {
        dispatch(clearCurrentToolId())
        setSelectedToolId(normalizeToolId(tool.toolId))
        safeSessionStorageRemoveItem('showToolQuestion')
        safeSessionStorageRemoveItem('currentToolId')
        setSessionToolId(null)
        setShowToolQuestion(false)
        onToolClick?.(true, undefined, displayName, false, undefined, undefined, pickToolMeta(tool))
        if (toolIdFromUrl) {
          const newSearchParams = new URLSearchParams(searchParams)
          newSearchParams.delete('toolId')
          setSearchParams(newSearchParams, { replace: true })
        }
      }
      else {
        if (tool.showStructuredQueryPlaceholder === true) {
          safeSessionStorageSetItem('showToolQuestion', 'true')
          setShowToolQuestion(true)
        }
        else {
          safeSessionStorageRemoveItem('showToolQuestion')
          setShowToolQuestion(false)
        }
        dispatch(setCurrentToolId(normalizedToolId))
        setSelectedToolId(normalizedToolId)
        safeSessionStorageSetItem('currentToolId', normalizedToolId)
        setSessionToolId(normalizedToolId)
      }

      await waitForToken()
      const res = await fetchSessionConversationId({ busiId: busiIdForSession })
      if (res?.data?.conversationId) {
        const conversationId = res.data.conversationId
        onToolClick?.(
          parentIsToolBtn,
          eventToolId,
          displayName,
          shouldChangeStyleForParent,
          conversationId,
          undefined,
          pickToolMeta(tool),
        )
        sessionStorage.setItem('toolHistoryLoading', conversationId)

        if (isGeneral) {
          navigate(`/chat/${conversationId}`, {
            replace: true,
            state: {
              toolId: null,
              skipHistoryLoad: true,
            },
          })
        }
        else {
          navigate(`/chat/${conversationId}?toolId=${normalizedToolId}`, {
            replace: true,
            state: {
              toolId: normalizedToolId,
              skipHistoryLoad: true,
            },
          })
        }

        await waitForToken()
        const qaToolIdArg = isGeneral ? '' : normalizedToolId
        const qaRes = await fetchUserQaRecordPage(conversationId, qaToolIdArg)
        console.log('qaRes chatEditor11111', qaRes)
        window.dispatchEvent(new CustomEvent('toolHistoryLoaded', {
          detail: {
            conversationId,
            toolId: isGeneral ? '' : normalizedToolId,
            toolName: displayName,
            qaRecords: qaRes?.data || [],
          },
        }))

        const qaList = Array.isArray(qaRes?.data) ? qaRes.data : []
        if (!hasQaWorkflowContext(qaList)) {
          const pair = getToolQuestionPairFromRow(tool)
          if (pair.recordType) {
            try {
              sessionStorage.setItem('pendingWorkflowSilentBootstrap', JSON.stringify({
                conversationId,
                toolId: isGeneral ? '' : normalizedToolId,
                recordType: pair.recordType,
                busiType: '01',
              }))
            }
            catch {
              // ignore
            }
          }
        }
        dispatch(fetchConversations(normalizedToolId))
        sessionStorage.removeItem('toolHistoryLoading')
      }
    }
    catch (error) {
      console.error('获取会话ID或历史记录失败:', error)
      sessionStorage.removeItem('toolHistoryLoading')
      if (!isGeneral) {
        onToolClick?.(false, eventToolId, displayName, shouldChangeStyleForParent, undefined, undefined, pickToolMeta(tool))
      }
    }
    finally {
      onToolClick?.(
        parentIsToolBtn,
        eventToolId,
        displayName,
        shouldChangeStyleForParent,
        undefined,
        false,
        pickToolMeta(tool),
      )
    }
  }

  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])

  // 仅进入带工具条的页面时拉取一次（含 5 分钟 session 缓存）；会话/路由切换不重复请求 get_tool_list
  useEffect(() => {
    if (!hideTools)
      void getToolList()
  }, [hideTools])

  // 监听 sessionStorage 中的 showToolQuestion
  useEffect(() => {
    const checkShowToolQuestion = () => {
      const value = safeSessionStorageGetItem('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)',
      ...(!hideTools && toolList && toolList.length > 0 ? { height: '102px' } : {}),
    }}
    >
      <div
        ref={editorRef}
        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={editorLocked ? undefined : handleKeyDown}
        onPaste={editorLocked ? undefined : handlePaste}
        contentEditable={!editorLocked}
        suppressContentEditableWarning
        data-placeholder={showToolQuestion ? '输入您想问的问题吧～' : '输入您想问的问题吧～'}
        style={{
          resize: 'none',
          maxHeight: '48px',
          wordBreak: 'break-all',
          ...(!hideTools && toolList && toolList.length > 0 ? { marginBottom: '40px' } : {}),
          ...(editorLocked ? { pointerEvents: 'none' as const, opacity: 0.5 } : {}),
        }}
      >
      </div>
      <Tooltip isOpen={Boolean(token) && showContentTips && !editorLocked && !content} color="foreground" content="请输入您的问题📖" placement="top-end">
        <Button className="ask-send" onPress={handleSubmit} radius="full" isDisabled={!content || editorLocked} 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>
      {!hideTools && toolList && toolList.length > 0 && (
        <div className="absolute left-4 bottom-2 flex items-center gap-3 pointer-events-auto pl-[16px]">
          {toolList.map((tool: ToolListRow, index: number) => {
            const toolIdStr = normalizeToolId(tool.toolId)
            const defaultToolId = toolList.length > 0 ? normalizeToolId(toolList[0].toolId) : null
            const activeToolId = selectedToolId ?? sessionToolId ?? toolIdFromUrl ?? defaultToolId
            const isSelected = activeToolId != null && toolIdStr === String(activeToolId)

            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
              await handleWorkflowToolButtonPress(tool)
            }

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

            return (
              <Button
                key={toolIdStr || `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)
