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

function FlatPickr(props: FieldProps) {

	const inputRef = useRef<HTMLInputElement>(null);

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

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

export default FlatPickr
