import { useEffect, useRef, useState } from "react"
import { AnimatePresence, motion, MotionProps } from "motion/react"

import { cn } from "@/lib/utils"

interface WordRotateProps {
  words: string[]
  duration?: number
  motionProps?: MotionProps
  className?: string
}

export function WordRotate({
  words,
  duration = 2500,
  motionProps = {
    initial: { opacity: 0, y: -50 },
    animate: { opacity: 1, y: 0 },
    exit: { opacity: 0, y: 50 },
    transition: { duration: 0.25, ease: "easeOut" },
  },
  className,
}: WordRotateProps) {
  const [index, setIndex] = useState(0)
  const [isPaused, setIsPaused] = useState(false)
  const intervalRef = useRef<NodeJS.Timeout | null>(null)

  useEffect(() => {
    if (isPaused) {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
        intervalRef.current = null
      }
      return
    }

    intervalRef.current = setInterval(() => {
      setIndex((prevIndex) => (prevIndex + 1) % words.length)
    }, duration)

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
        intervalRef.current = null
      }
    }
  }, [isPaused, words, duration])

  return (
    <div
      className="relative grid py-2"
      onMouseEnter={() => setIsPaused(true)}
      onMouseLeave={() => setIsPaused(false)}
    >
      {words.map((w) => (
        <span
          key={w}
          aria-hidden
          className={cn("invisible col-start-1 row-start-1 pointer-events-none select-none", className)}
        >
          {w}
        </span>
      ))}
      <div className="col-start-1 row-start-1 overflow-hidden">
        <AnimatePresence mode="wait">
          <motion.h1
            key={words[index]}
            className={cn(className)}
            {...motionProps}
          >
            {words[index]}
          </motion.h1>
        </AnimatePresence>
      </div>
    </div>
  )
}
