import { Tooltip } from '@heroui/react'
import type React from 'react'
import { Image } from '@heroui/image'
import { motion } from 'framer-motion'
import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Refresh from '@/assets/svg/refresh.svg?react'
import { type WithAuthProps, withAuth } from '@/auth/withAuth'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { createConversation, setCurrentConversation, setShouldSendQuestion } from '@/store/conversationSlice'
import { safeSessionStorageGetItem } from '@/lib/utils'
import emptyIcon from '@/assets/empty-icon.png'

interface QuestionListProps {
  title: string
  iconImg: string
  dotColor: string
  questions: string[]
  showRefresh?: boolean
  displayCount?: number
  background: string
  height?: string
  isToolBtn?: boolean
  isLoaded?: boolean
  onRefresh?: () => Promise<void>
}
const containerVariants = {
  hidden: {},
  visible: {},
}
const itemVariants = {
  hidden: { opacity: 0, x: 60, scale: 0.9 },
  visible: (i: number) => ({
    opacity: 1,
    x: 0,
    scale: 1,
    transition: {
      delay: i * 0.1,
      type: 'spring',
      stiffness: 180,
      damping: 25,
      mass: 0.9,
    },
  }),
  exit: {
    opacity: 0,
    x: 30,
    scale: 0.9,
    transition: { duration: 0.15 },
  },
}

function getRandomIndices(total: number, count: number): number[] {
  const indices = new Set<number>()
  while (indices.size < count) {
    indices.add(Math.floor(Math.random() * total))
  }
  return Array.from(indices)
}

const QuestionListBase: React.FC<QuestionListProps & WithAuthProps> = ({
  checkAuth,
  questions,
  dotColor,
  background,
  height,
  title,
  iconImg,
  showRefresh = true,
  displayCount: _displayCount = 6,
  isToolBtn = false,
  isLoaded = false,
  onRefresh,
}) => {
  const [isRotating, setIsRotating] = useState(false)
  const [displayedItems, setDisplayedItems] = useState<string[]>([])
  const [isClicking, setIsClicking] = useState(false)
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const { currentConversationId, conversations, currentToolId } = useAppSelector(state => state.conversation)

  // 根据 isToolBtn 动态设置 displayCount
  const actualDisplayCount = isToolBtn ? 6 : 4

  const updateDisplayedItems = useCallback(() => {
    const indices = getRandomIndices(questions.length, Math.min(actualDisplayCount, questions.length))
    setDisplayedItems(indices.map(index => questions[index]))
  }, [questions, actualDisplayCount])

  const handleRefresh = async () => {
    // 如果没有提供 onRefresh 回调，则不执行任何操作
    if (!onRefresh) {
      return
    }

    setIsRotating(true)
    try {
      // 重新调用接口获取新问题
      await onRefresh()
    }
    catch (error) {
      console.error('刷新问题列表失败:', error)
      // 接口调用失败时不回退到随机选择，保持当前状态
    }
    finally {
      setIsRotating(false)
    }
  }
  const handleClick = (item: string) => {
    if (checkAuth() && !isClicking) {
      setIsClicking(true)
      // 获取当前的 toolId，优先从 Redux 获取，其次从 sessionStorage 获取
      const toolId = currentToolId || safeSessionStorageGetItem('currentToolId') || null
      // 优先使用当前会话，如果没有则使用第一个会话，如果都没有则创建新会话
      const targetConversationId = currentConversationId || conversations[0]?.conversationId
      if (targetConversationId) {
        // 使用现有会话
        dispatch(setCurrentConversation(targetConversationId))
        dispatch(setShouldSendQuestion(item))
        // 通过 location.state 传递 toolId，避免 Chat 页面清空 toolId
        navigate(`/chat/${targetConversationId}`, {
          state: {
            toolId,
          },
        })
      }
      else {
        // 如果没有现有会话，仍然创建新会话（向后兼容）
        // 这里可以改为提示用户，或者保持创建新会话的逻辑
        // 为了最小修改，暂时保持创建新会话的逻辑
        dispatch(
          createConversation({
            conversationData: {},
            shouldNavigate: true,
            shouldSendQuestion: item,
          }),
        )
      }
      // 防止重复点击
      setTimeout(() => {
        setIsClicking(false)
      }, 1000)
    }
  }

  useEffect(() => {
    updateDisplayedItems()
  }, [updateDisplayedItems])

  // 当上游将 questions 清空时，立即清空展示项，避免短暂显示旧数据
  const itemsToRender = questions.length === 0 ? [] : displayedItems

  return (
    <div
      className="bg-white box-border px-[20px] py-[12px] w-full sm:w-[300px] md:w-[300px]"
      style={{ background, height }}
    >
      <h3 className="flex items-center justify-between whitespace-nowrap">
        <div className="flex items-center min-w-0 flex-1 h-full">
          <Image className="w-[28px] h-[28px] flex-shrink-0" src={iconImg} alt="" />
          <div className="text-[15px] mt-[4px] ml-[12px] font-medium overflow-hidden text-ellipsis whitespace-nowrap flex-1 min-w-0">
            {isToolBtn ? '常见问题' : title}
          </div>
        </div>
        {showRefresh
? (
          <div onClick={handleRefresh} className="flex-shrink-0 ml-[8px] flex items-center gap-[4px]">
            <div className="cursor-pointer">
              <motion.div
                animate={{ rotate: isRotating ? -360 : 0 }}
                transition={{
                  duration: 0.1,
                  ease: 'linear',
                  repeat: isRotating ? Infinity : 0,
                }}
              >
                <Refresh className="w-[12px] h-[12px]" />
              </motion.div>
            </div>
            <div className="text-[12px] text-[#29B6FD] cursor-pointer">换一换</div>
          </div>
        )
: null}
      </h3>
      {((isLoaded && questions && questions.length === 0) || (isToolBtn && (!questions || questions.length === 0)))
        ? (
            <div className="mt-[34px] flex flex-col items-center justify-center h-[200px]">
              <div className="flex flex-col items-center">
                <Image src={emptyIcon} alt="空数据" className="w-[72px] h-[72px]" />
                <div className="mt-[16px] text-[14px] text-[#27353C]">问题正在路上...</div>
              </div>
            </div>
          )
        : (
        <motion.ul
          key={displayedItems.join(',')}
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          className="mt-[8px] flex flex-col gap-[8px] w-full"
        >
          {itemsToRender.map((item, index) => (
            <motion.li
              key={`question-${item}`}
              custom={index}
              variants={itemVariants}
              initial="hidden"
              animate="visible"
              exit="exit"
              layout
              className="w-full"
            >
              <Tooltip
                color="foreground"
                content={item}
                placement="top"
                // 鼠标移出后尽快关闭 Tooltip，避免停留过长
                closeDelay={0}
              >
                <button
                  type="button"
                  onClick={() => handleClick(item)}
                  className="group w-full h-8 px-[14px] rounded-[23px] bg-[#F8FBFF] text-[#333] text-left flex items-center transition-colors hover:bg-[#F0F8FF] hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#29B6FD]/40"
                >
                  <span className="w-[6px] h-[6px] rounded-full inline-block mr-[6px]" style={{ backgroundColor: dotColor }}></span>
                  <span className="ml-[8px] truncate group-hover:text-primary text-[14px]">{item}</span>
                </button>
              </Tooltip>
            </motion.li>
          ))}
        </motion.ul>
          )}
    </div>
  )
}

export const QuestionList = withAuth(QuestionListBase)
