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,
		settings: { tilt, remoteTilt },
		setTilt,
		tilt: localTilts,
	} = useAppContext();

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

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

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

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

				if (rotateX || rotateY) {
					card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
				} else {
					card.style.transform = `rotateX(0deg) rotateY(0deg)`;
				}
			} else {
				console.log(localTilts);
				const rotateX = localTilts[cardIndex]?.rotateX || 0;
				const rotateY = localTilts[cardIndex]?.rotateY || 0;

				if (rotateX || rotateY) {
					card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
				} else {
					card.style.transform = `rotateX(0deg) rotateY(0deg)`;
				}
			}
		} else if (card.style.transform !== 'rotateX(0deg) rotateY(0deg)') {
			card.style.transform = 'rotateX(0deg) rotateY(0deg)';
		}
	}, [tilt, localTilts, 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={tilt ? handleMouseMove : undefined}
			onMouseLeave={handleMouseLeave}
		>
			<div ref={cardRef} className={`h-full w-full transition-transform duration-0`}>
				{children}
			</div>
		</div>
	);
}
