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
}
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, title, iconImg, showRefresh = true, displayCount = 4 }) => {
  const [isRotating, setIsRotating] = useState(false)
  const [displayedItems, setDisplayedItems] = useState<string[]>([])
  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()) {
      dispatch(createConversation({
        conversationData: {},
        shouldNavigate: true,
        shouldSendQuestion: item,
      }))
    }
  }

  useEffect(() => {
    updateDisplayedItems()
  }, [updateDisplayedItems])
  return (
    <div className="h-[276px] bg-white box-border px-[20px] py-[24px] rounded-[24px] w-full sm:w-[360px] md:w-[300px]">
      <h3 className="h-[32px] flex items-center justify-between">
        <div className="flex items-center">
          <Image className="w-[32px] h-[32px]" src={iconImg} alt="" />
          <span className="text-[18px] ml-[12px] font-medium">{title}</span>
        </div>
        {
          showRefresh
            ? (
                <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>
              )
            : null

        }

      </h3>
      <motion.ul
        key={displayedItems.join(',')}
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="mt-[18px] flex flex-col gap-[8px] w-full"
      >
        {
          displayedItems.map((item, index) => (
            <motion.li
              key={`${item}-${index}`}
              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">
                <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)
