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'
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
}
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,
}) => {
  const [isRotating, setIsRotating] = useState(false)
  const [displayedItems, setDisplayedItems] = useState<string[]>([])
  const [isClicking, setIsClicking] = useState(false)
  const dispatch = useAppDispatch()

  // 根据 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 = () => {
    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">
            {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
        ? (
            <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"
        >
          {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)
