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

function FlatPickr(props: FieldProps) {

	const inputRef = useRef<HTMLInputElement>(null);

	useEffect(() => {
		const element = inputRef.current as HTMLInputElement;
		const fp = flatpickr(element, {
			plugins: [weekSelect() as any],
			minDate: props.min,
			maxDate: props.max,
			defaultDate: props.value,
			weekNumbers: true,
			dateFormat: '\\Week W, Y',
		});
		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
