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

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

	const card = cardRef.current;

	useEffect(() => {
		if (!card) return;

		const tilt = tilts.find((tilt) => tilt.cardID === cardID);
		if (!tilt) {
			card.style.transform = `rotateX(0deg) rotateY(0deg)`;
			return;
		}

		const { rotateX, rotateY } = tilt;

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

	const handleMouseMove = (e: React.MouseEvent) => {
		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;

		setTilts([...tilts.filter((tilt) => tilt.cardID !== cardID), { cardID, rotateX, rotateY }]);
	};

	const handleMouseLeave = () => {
		if (!card) return;

		setTilts(tilts.filter((tilt) => tilt.cardID !== cardID));
	};

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