import { motion } from 'framer-motion'
import { Button } from '@heroui/react'
import { useNavigate } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { containerVariants, itemVariants } from '../../motionAnimate'
import EmptyIcon from '@/assets/svg/empty.svg?react'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import type { Conversation } from '@/types/conversation'
import { processConversationData } from '@/store/conversationSlice.helper'
import { clearCurrentToolId, clearShouldSendQuestion, setCurrentToolId, setShouldSendQuestion } from '@/store/conversationSlice'
import { isMobile } from '@/utils'

interface HistoryBarListProps {
  searchValue: string
  onSetHistoryVisible: (visible: boolean) => void
}

export const HistoryBarList: React.FC<HistoryBarListProps> = ({ searchValue, onSetHistoryVisible }) => {
  const navigate = useNavigate()
  const { currentConversationId, conversations } = useAppSelector(state => state.conversation)
  const [allItems, setAllItems] = useState<Conversation[]>([])
  const dispatch = useAppDispatch()

  const handleClick = (conversation: Conversation) => {
    if (isMobile()) {
      onSetHistoryVisible(false)
    }

    console.log('88888888888:', conversation, {
      conversationId: conversation.conversationId,
      toolId: conversation.toolId,
    })
    if (conversation.toolId) {
      sessionStorage.setItem('currentToolId', conversation.toolId)
      console.log('[chat-toolid-log] HistoryBarList setItem:', conversation.toolId, '| line:35')
      dispatch(setCurrentToolId(conversation.toolId))
    }
    else {
      sessionStorage.removeItem('currentToolId')
      console.log('[chat-toolid-log] HistoryBarList removeItem', '| line:39')
      dispatch(clearCurrentToolId())
    }

    // 仅当历史记录为“提质增效”时，进入对话页后自动触发一次提问接口
    // 用空格字符串触发 shouldSendQuestion 的监听，但不会在 UI 中新增用户问题气泡（question.trim() 为 false）。
    const isQualityImprovement = conversation.toolId === '6712395743241'
    const isBusinessInsight = conversation.toolId === '6712395743242'
    console.log('工具ID:', {
      conversationId: conversation.conversationId,
      toolId: conversation.toolId,
      isQualityImprovement,
      isBusinessInsight,
      willAutoSubmitByShouldSendQuestion: isQualityImprovement,
    })
    if (isQualityImprovement) {
      const autoShouldSendQuestion = ' '
      dispatch(setShouldSendQuestion(autoShouldSendQuestion))
      console.log('[HistoryBarList] shouldSendQuestion 000000:', {
        conversationId: conversation.conversationId,
        toolId: conversation.toolId,
        shouldSendQuestion: autoShouldSendQuestion,
      })
    }
    else {
      // 避免上一次残留的 shouldSendQuestion 误触发自动提问
      console.log('工具ID:2', {
        conversationId: conversation.conversationId,
        toolId: conversation.toolId,
      })
      dispatch(clearShouldSendQuestion())
    }
    // 直接导航到历史记录，不设置shouldSendQuestion
    // 在 URL 中拼接 toolId 作为查询参数，以便刷新页面后仍能保留
    const url = conversation.toolId
      ? `/chat/${conversation.conversationId}?toolId=${conversation.toolId}`
      : `/chat/${conversation.conversationId}`
    navigate(url, {
      state: {
        toolId: conversation.toolId || null,
      },
    })

    // 通知首页根据对应 toolId 重新拉取常见问题（与底部工具按钮保持一致逻辑）
    window.dispatchEvent(new CustomEvent('toolButtonClick', {
      detail: {
        // 有 toolId 表示工具模式，没 toolId 表示制度活化
        isToolBtn: !conversation.toolId,
        toolId: conversation.toolId || '',
        toolName: '',
        shouldChangeStyle: true,
        conversationId: conversation.conversationId,
      },
    }))
  }

  const handleFilter = useDebounceFn(() => {
    const _allItems = conversations.filter(item => item.conversationTitle.includes(searchValue))
    setAllItems(processConversationData(_allItems))
  }, { wait: 300 })

  useEffect(() => {
    handleFilter.run()
  }, [searchValue])

  return (
    allItems.length !== 0
      ? (
        <motion.ul
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          className="w-full flex flex-col gap-[6px]"
        >
          {
            allItems.map((item, index) => (
              <motion.li
                key={item.conversationId || `item-${item.conversationTitle}`}
                custom={index}
                variants={itemVariants}
                initial="hidden"
                animate="visible"
                exit="exit"
                layout
              >
                {
                  item.conversationId
                    ? (
                      <Button
                        color="primary"
                        variant="light"
                        className={`text-left w-full text-[#333] rounded-[23px] data-[hover=true]:bg-[#E5F6FF] data-[hover=true]:text-primary ${currentConversationId === item.conversationId ? 'bg-[#E5F6FF] text-primary' : ''}`}
                        onPress={() => handleClick(item)}
                      >
                        <div className="w-full text-nowrap text-ellipsis overflow-hidden">
                          <span>{item.conversationTitle}</span>
                        </div>
                      </Button>
                    )
                    : (
                      <div className="mt-[32px] text-[13px] text-[#B1C6D2]">{item.conversationTitle}</div>
                    )
                }

              </motion.li>
            ))
          }
        </motion.ul>
      )
      : (
        <div className="flex w-full h-full items-center justify-center flex-col">
          <EmptyIcon />
          <p className="text-[13px] text-[#27353C] mt-[16px]">暂无历史记录</p>
        </div>
      )
  )
}
