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

const FlatPickr = lazy(() => import("./FlatPickr"));

export type FieldProps = {
	itemId: string
	formId: string
	attrs: Record<string, string | string[]>
	value: string
	min: string
	max: string
	placeholder: string
}

const Field = (props: FieldProps) => {

	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]);

	const nativeInput = (
		<input
			ref={inputRef}
			type="text"
			{...attrs}
			{...(props.min && {
				min: props.min,
			})}
			{...(props.max && {
				max: props.max,
			})}
			value={value}
			placeholder={props.placeholder}
			onChange={(event) => {
				setValue(event.target.value);
			}}
		/>
	)

	return (
		<Suspense fallback={nativeInput}>
			<FlatPickr {...props} attrs={attrs}/>
		</Suspense>
	)
};

export default Field;
