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
	isNative: boolean
	time_24hr: boolean
}

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="datetime-local"
			{...attrs}
			{...(props.min && {
				min: props.min,
			})}
			{...(props.max && {
				max: props.max,
			})}
			value={value}
			placeholder={props.placeholder}
			onChange={(event) => {
				setValue(event.target.value);
			}}
		/>
	)

	if (props.isNative) {
		return nativeInput;
	}

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

export default Field;
