import { Button } 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 Refresh from '@/assets/svg/refresh.svg?react'
import { type WithAuthProps, withAuth } from '@/auth/withAuth'
import { useAppDispatch } from '@/store/hook'
import { createConversation } from '@/store/conversationSlice'

interface QuestionListProps {
  title: string
  iconImg: string
  dotColor: string
  questions: string[]
  showRefresh?: boolean
  displayCount?: number
  background: string
  height?: string
  isToolBtn?: boolean
}
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 = 8,
  isToolBtn = false,
}) => {
  const [isRotating, setIsRotating] = useState(false)
  const [displayedItems, setDisplayedItems] = useState<string[]>([])
  const [isClicking, setIsClicking] = useState(false)
  const dispatch = useAppDispatch()

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

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

  const handleRefresh = () => {
    setIsRotating(true)
    updateDisplayedItems()
    setIsRotating(false)
  }
  const handleClick = (item: string) => {
    if (checkAuth() && !isClicking) {
      setIsClicking(true)
      dispatch(
        createConversation({
          conversationData: {},
          shouldNavigate: true,
          shouldSendQuestion: item,
        }),
      )
      // 防止重复点击
      setTimeout(() => {
        setIsClicking(false)
      }, 1000)
    }
  }

  useEffect(() => {
    updateDisplayedItems()
  }, [updateDisplayedItems])
  return (
    <div
      className="bg-white box-border px-[20px] py-[12px] rounded-[24px] 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">
            {title}
          </div>
        </div>
        {showRefresh
? (
          <div className="flex-shrink-0 ml-[8px]">
            <Button onPress={handleRefresh} isDisabled={isRotating} isIconOnly color="primary" variant="light">
              <motion.div
                animate={{ rotate: isRotating ? -360 : 0 }}
                transition={{
                  duration: 0.7,
                  ease: 'linear',
                  repeat: isRotating ? Infinity : 0,
                }}
              >
                <Refresh />
              </motion.div>
            </Button>
          </div>
        )
: null}
      </h3>
      <motion.ul
        key={displayedItems.join(',')}
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="mt-[8px] flex flex-col gap-[8px] w-full"
      >
        {displayedItems.map((item, index) => (
          <motion.li
            key={`question-${item}`}
            custom={index}
            variants={itemVariants}
            initial="hidden"
            animate="visible"
            exit="exit"
            layout
            className="w-full"
          >
            <Button
              onPress={() => handleClick(item)}
              color="primary"
              variant="light"
              className="text-left bg-[#F8FBFF] w-full text-[#333] rounded-[23px] data-[hover=true]:bg-[#F0F8FF] data-[hover=true]:text-primary h-8"
            >
              <div className="w-full text-nowrap text-ellipsis overflow-hidden">
              <span className="w-[6px] h-[6px] rounded-full inline-block mr-[6px]" style={{ backgroundColor: dotColor }}></span>
                <span className="ml-[8px]">{item}</span>
              </div>
            </Button>
          </motion.li>
        ))}
      </motion.ul>
    </div>
  )
}

export const QuestionList = withAuth(QuestionListBase)
