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, setCurrentToolId } 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)
      dispatch(setCurrentToolId(conversation.toolId))
    }
    else {
      sessionStorage.removeItem('currentToolId')
      dispatch(clearCurrentToolId())
    }
    // 直接导航到历史记录，不设置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>
      )
  )
}
