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
}
const containerVariants = {
  hidden: {},
  visible: {},
}
const itemVariants = {
  hidden: { opacity: 0, y: 20, scale: 0.8 },
  visible: (i: number) => ({
    opacity: 1,
    y: 0,
    scale: 1,
    transition: {
      delay: i * 0.08,
      type: 'spring',
      stiffness: 200,
      damping: 20,
      mass: 0.8,
    },
  }),
  exit: {
    opacity: 0,
    scale: 0.8,
    transition: { duration: 0.2 },
  },
}

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

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

  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-[360px] md:w-[300px]"
      style={{ background }}
    >
      <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-[#F7FCFF] w-full text-[#333] rounded-[23px] data-[hover=true]:bg-[#E5F6FF] data-[hover=true]:text-primary h-8"
            >
              <div className="w-full text-nowrap text-ellipsis overflow-hidden">
                <span style={{ color: dotColor }}>·</span>
                <span className="ml-[8px]">{item}</span>
              </div>
            </Button>
          </motion.li>
        ))}
      </motion.ul>
    </div>
  )
}

export const QuestionList = withAuth(QuestionListBase)
