import {createElement, useLayoutEffect, useRef, useState} from 'react';

import './entry.css';

function TextField({ item, onEnter, onSelect, onRemove, ref }) {
	const onKeyDown = e => {
		if (e.keyCode === 38) { // up
			onSelect(-1);
			e.preventDefault();
			return;
		} else if (e.keyCode === 40) { // down
			onSelect(+1);
			e.preventDefault();
			return;
		} else if (e.keyCode === 8 && e.target.innerText.length === 0) { // backspace
			onRemove();
			e.preventDefault();
			return;
		}

		if (e.keyCode !== 13) {
			return;
		} else if (e.shiftKey) {
			return;
		}

		e.preventDefault();

		onEnter(e.ctrlKey ? 'todo' : 'plain');
	};

	useLayoutEffect(() => {
		if (ref.current == null) {
			return;
		}

		ref.current.innerText = item.text;
	}, [item.text]);

	return <div ref={ref} className='text' contentEditable="true" onKeyDown={onKeyDown} onClick={() => onSelect(0)}></div>;
}

function Plain({ item, onEnter, onSelect, onRemove, ref }) {
	return <TextField item={item} onEnter={onEnter} onSelect={onSelect} onRemove={onRemove} ref={ref} />;
}

function Todo({ item, onEnter, onSelect, onRemove, ref }) {
	return <>
		<input type="checkbox" />
		<TextField item={item} onEnter={onEnter} onSelect={onSelect} onRemove={onRemove} ref={ref} />
	</>;
}

export default function Entry({ item, onEnter, onSelect, onRemove, isFocused }) {
	const ref = useRef(null);
	useLayoutEffect(() => {
		if (isFocused && ref.current != null && document.activeElement !== ref.current) {
			ref.current.focus();
			document.execCommand('selectAll', false, null);
			document.getSelection().collapseToEnd();
		}
	}, [isFocused]);

	const child = createElement(item.type === 'plain' ? Plain : Todo, {
		ref,
		item,
		onEnter,
		onSelect,
		onRemove: () => onRemove(true),
	});

	return <div className={`entry ${isFocused ? 'focus' : ''}`}>
		<button onClick={() => onRemove(false)}>X</button>
		{child}
	</div>
}
