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

const ZERO_ROTATION = 'rotateX(0deg) rotateY(0deg)';

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) {
			const rotateX = localTilts[cardIndex]?.rotateX || 0;
			const rotateY = localTilts[cardIndex]?.rotateY || 0;

			const tilts = remoteTilt
				? [...gameData.tilts[cardIndex], { rotateX, rotateY }]
				: [{ rotateX, rotateY }];

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

			if (count && (totalX || totalY)) {
				card.style.transform = `rotateX(${totalX / count}deg) rotateY(${totalY / count}deg)`;
			} else {
				card.style.transform = ZERO_ROTATION;
			}
		} else if (card.style.transform !== ZERO_ROTATION) {
			card.style.transform = ZERO_ROTATION;
		}
	}, [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>
	);
}
