import { useEffect, useRef } from 'react';
import { useAppContext } from '@/app/AppContext';
import type { Tilt } from '@/types';

export default function TiltCard({
	children,
	cardIndex,
	className = '',
}: {
	children: React.ReactNode;
	cardIndex: number;
	className?: string;
}) {
	const cardRef = useRef<HTMLDivElement>(null);
	const { gameData, setTilt } = useAppContext();

	useEffect(() => {
		const card = cardRef.current;
		if (!card) return;

		const tilt = gameData.tilts[cardIndex];
		if (!tilt) {
			card.style.transform = `rotateX(0deg) rotateY(0deg)`;
			return;
		}

		const tilted = tilt.filter(({ rotateX, rotateY }) => rotateX || rotateY);

		const { totalX, totalY } = tilted.reduce(
			({ totalX, totalY }, { rotateX, rotateY }) => ({
				totalX: totalX + rotateX,
				totalY: totalY + rotateY,
			}),
			{ totalX: 0, totalY: 0 },
		);

		const rotateX = totalX / tilted.length;
		const rotateY = totalY / tilted.length;

		if (rotateX || rotateY) {
			card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
		} else {
			card.style.transform = `rotateX(0deg) rotateY(0deg)`;
		}
	}, [gameData]);

	const handleMouseMove = (e: React.MouseEvent) => {
		const card = cardRef.current;
		if (!card) return;

		const rect = card.getBoundingClientRect();
		const x = e.clientX - rect.left;
		const y = e.clientY - rect.top;
		const centerX = rect.width / 2;
		const centerY = rect.height / 2;

		const rotateX = ((y - centerY) / centerY) * -20;
		const rotateY = ((x - centerX) / centerX) * 20;

		const newTilt: Tilt[] = [];
		newTilt[cardIndex] = { rotateX, rotateY };

		setTilt(newTilt);
	};

	const handleMouseLeave = () => {
		setTilt([]);
	};

	return (
		<div className={`${className}`} onMouseMove={handleMouseMove} onMouseLeave={handleMouseLeave}>
			<div ref={cardRef} className={`h-full w-full transition-transform duration-0`}>
				{children}
			</div>
		</div>
	);
}
