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)
    }
    if (conversation.toolId) {
      dispatch(setCurrentToolId(conversation.toolId))
    }
    else {
      dispatch(clearCurrentToolId())
    }
    // 直接导航到历史记录，不设置shouldSendQuestion
    navigate(`/chat/${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>
      )
  )
}
