import {useMemo, useRef, useState} from 'react';
import renderHtmlAttributes from "../../utils/renderHtmlAttributes";
import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess";
import UpgradeOverlay from "../../components/UpgradeOverlay";
import type {FreemiusProps} from "../../types/freemius";
import Scanner from "./Scanner";

export type FieldProps = {
	itemId: string
	formId: string
	attrs: Record<string, string | string[]>
	value: string
	icon: string
} & FreemiusProps

const Field = (props: FieldProps) => {

	const containerRef = useRef<HTMLDivElement>(null);
	const inputRef = useRef<HTMLInputElement>(null);
	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);

	const [value, setValue] = useState(props.value);

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

	function handleError(error: string) {
		const container = containerRef.current as HTMLDivElement;
		const messageElement = container.parentElement?.querySelector('.elementor-message');
		if (messageElement) {
			messageElement.textContent = error;
		} else {
			const messageCreate = document.createElement('span');
			messageCreate.classList.add('elementor-message', 'elementor-message-danger');
			messageCreate.textContent = error;
			container.parentElement?.appendChild(messageCreate);
		}
	}

	return (
		<>
			{!props.freemius.can_use_premium_code && <UpgradeOverlay url={props.freemius.get_upgrade_url}/>}
			<div ref={containerRef} className="hulk-barcode-input-wrap">
				<input
					ref={inputRef}
					{...attrs}
					id={`${attrs.id}-barcode`}
					value={value}
					onChange={(e) => {
						setValue(e.target.value);
					}}
				/>
				<Scanner
					{...props}
					attrs={attrs}
					onResult={(val) => setValue(val)}
					onError={handleError}
				/>
			</div>
			<div id={attrs.id}/>
		</>
	);
};

export default Field;
