import { useCallback, useEffect, useRef, useState } from 'react';
import { motion } from 'framer-motion';

function Ruler(props) {
	const ruler = useRef(null);
	const [left, setLeft] = useState(props.left || '100px');
	const [top, setTop] = useState(props.top || '100px');
	const [dragging, setDragging] = useState(false);
	const isVertical = props.type == 'vertical';
	const handleUp = useCallback(() => {
		setDragging(false);
	}, []);
	const handleMove = useCallback(
		(e) => {
			if (!dragging) return;
			const v = isVertical ? e.clientX : e.clientY;
			isVertical ? setLeft(v + 'px') : setTop(v + 'px');
		},
		[dragging],
	);

	useEffect(() => {
		document.addEventListener('mouseup', handleUp);
		document.addEventListener('mousemove', handleMove);

		return () => {
			document.removeEventListener('mouseup', handleUp);
			document.removeEventListener('mousemove', handleMove);
		};
	}, [dragging]);

	function handleMouseDown() {
		setDragging(true);
	}

	return (
		<motion.div
			ref={ruler}
			className="ruler-line"
			style={{
				position: 'fixed',
				top: isVertical ? 0 : top,
				left: isVertical ? left : 0,
				overflow: 'visible',
				height: isVertical ? '100vh' : '1px',
				width: isVertical ? '1px' : '100vw',
				cursor: 'pointer',
				userSelect: 'none',
				background: props.background || '#ccc',
			}}
			onMouseDown={handleMouseDown}
		>
			<div
				className="ruler-tooltip"
				style={{
					position: 'absolute',
					top: isVertical ? '200px' : '20px',
					right: isVertical ? '-132px' : '50px',
					width: '128px',
					border: '1px solid #0008',
					padding: '0 12px',
					background: '#ecc100',
					color: '#0008',
				}}
			>
				{isVertical ? `left: ${left}` : `top: ${top}`}
			</div>
		</motion.div>
	);
}

function RulerContainer(props) {
	const [rulers, setRulers] = useState([]);

	// 监听事件
	useEffect(() => {
		let fn = (e) => {
			if (e.shiftKey && e.key === 'R') {
				setRulers((rulers) => [
					...rulers,
					{
						width: '1px',
						height: '100vh',
						background: '#ccc',
						type: 'vertical',
					},
				]);
			}
			if (e.shiftKey && e.key === 'H') {
				setRulers((rulers) => [
					...rulers,
					{ width: '100vw', height: '1px', background: '#ccc' },
				]);
			}
			if (e.shiftKey && e.key === 'Q') {
				setRulers((rulers) => []);
			}
		};

		document.addEventListener('keydown', fn);
	}, []);

	return (
		<div
			id="ruler-container"
			style={{ position: 'fixed', top: 0, left: 0, width: 0, height: 0 }}
		>
			{rulers.map((ruler) => (
				<Ruler key={Math.random()} {...ruler} />
			))}
		</div>
	);
}

export default RulerContainer;
