import {useEffect, useRef} from "react";
import flatpickr from "flatpickr";
import type {FieldProps} from "./Field";

function FlatPickr(props: FieldProps) {

	const inputRef = useRef<HTMLInputElement>(null);

	useEffect(() => {
		const element = inputRef.current as HTMLInputElement;
		const fp = flatpickr(element, {
			enableTime: true,
			minDate: props.min,
			maxDate: props.max,
			time_24hr: props.time_24hr,
			defaultDate: props.value
		});
		return () => {
			fp?.destroy();
		}
	}, [props.max, props.min, props.time_24hr, props.value]);

	return (
		<input
			ref={inputRef}
			type="text"
			{...props.attrs}
			placeholder={props.placeholder}
			defaultValue={props.value}
		/>
	)
}

export default FlatPickr
