import { AnimatePresence, motion } from 'framer-motion';
import Image from 'next/image';
import { useCallback, useState } from 'react';

export interface FloatingIcon {
  id: string;
  profileUrl: string;
  x: number;
  y: number;
  styleIndex: number;
}

interface FloatingVoteIconProps {
  icons: FloatingIcon[];
  onAnimationComplete: (iconId: string) => void;
}

export function FloatingVoteIcon({
  icons,
  onAnimationComplete,
}: FloatingVoteIconProps) {
  return (
    <AnimatePresence>
      {icons.map((icon) => (
        <motion.div
          key={icon.id}
          className='pointer-events-none fixed z-50'
          initial={{
            left: icon.x,
            top: icon.y,
            x: '-50%',
            y: '-50%',
            opacity: 1,
            scale: 1,
          }}
          animate={{
            top: icon.y - 120,
            opacity: 0,
            scale: 0.5,
          }}
          exit={{
            opacity: 0,
            scale: 0,
          }}
          transition={{
            duration: 2.5,
            ease: 'easeOut',
          }}
          onAnimationComplete={() => onAnimationComplete(icon.id)}
        >
          <Image
            src={icon.profileUrl}
            alt='Voter'
            className='h-8 w-8 rounded-full border-2 border-white/20 shadow-lg'
            width={32}
            height={32}
            onError={(e) => {
              // Fallback to default avatar if image fails to load
              e.currentTarget.style.display = 'none';
            }}
          />
        </motion.div>
      ))}
    </AnimatePresence>
  );
}

// Custom hook to manage floating icons
export function useFloatingIcons() {
  const [floatingIcons, setFloatingIcons] = useState<FloatingIcon[]>([]);

  const addFloatingIcon = useCallback(
    (profileUrl: string, styleIndex: number, buttonRect: DOMRect) => {
      const randomOffset = (Math.random() - 0.5) * 50; // Random horizontal offset
      const newIcon: FloatingIcon = {
        id: `vote-${Date.now()}-${Math.random()}`,
        profileUrl,
        x: buttonRect.left + buttonRect.width / 2 + randomOffset,
        y: buttonRect.top + buttonRect.height / 2,
        styleIndex,
      };
      setFloatingIcons((prev) => [...prev, newIcon]);
    },
    []
  );

  const removeFloatingIcon = useCallback((iconId: string) => {
    setFloatingIcons((prev) => prev.filter((icon) => icon.id !== iconId));
  }, []);

  return {
    floatingIcons,
    addFloatingIcon,
    removeFloatingIcon,
  };
}
