import {type ChangeEvent, useMemo, useRef, useState} from 'react';
import renderHtmlAttributes from "../../utils/renderHtmlAttributes";
import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess";

type FieldProps = {
	formId: string
	itemId: string
	showInput: boolean
	attrs: Record<string, string | string[]>
}

const Field = (props: FieldProps) => {

	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);

	const defaultValue = useMemo(() => {
		const max = Number(props.attrs.max);
		const min = Number(props.attrs.min);
		return max < min ? min : min + (max - min) / 2;
	}, [props.attrs.max, props.attrs.min]);

	const initialValue = useMemo(() => {
		return attrs.value?.trim() || defaultValue.toString();
	}, [attrs.value, defaultValue]);

	const inputRef = useRef<HTMLInputElement>(null);
	const [value, setValue] = useState(initialValue);

	function handleRange(event: ChangeEvent<HTMLInputElement>) {
		setValue(event.target.value);
	}

	function handleInput(event: ChangeEvent<HTMLInputElement>) {
		setValue(event.target.value);
	}

	// Reset after form submit
	useFormSubmitSuccess(inputRef, () => {
		setValue(initialValue);
	}, [initialValue])

	return (
		<>
			<div className="hulk-range-input-wrap">
				<input
					ref={inputRef}
					{...attrs}
					type="range"
					value={value}
					onChange={handleRange}
				/>
			</div>
			{props.showInput && (
				<div className={'hulk-show-input-wrap'}>
					<input
						type="number"
						className="elementor-field elementor-field-textual hulk-show-input"
						value={value}
						onChange={handleInput}
						min={attrs.min}
						max={attrs.max}
						step={attrs.step}
					/>
				</div>
			)}
		</>
	);
};

export default Field;
