import { useEffect, useRef, useState } from "react";

import isEqual from "lodash.isequal";

const useShouldBeSaved = (
	selected: any | null,
	form: any | null,
): { isDirty: boolean; setIsDirty: (isDirty: boolean) => void } => {
	const formRef = useRef();
	const [isDirty, setIsDirty] = useState(false);
	const savedValues = selected?.config && JSON.stringify(selected.config);
	const stringValue = form && JSON.stringify(form);

	// biome-ignore lint/correctness/useExhaustiveDependencies: TODO: fix this
	useEffect(() => {
		if (!formRef.current) {
			formRef.current = stringValue && JSON.parse(stringValue);
		}
		const stringFormRef = formRef.current && JSON.stringify(formRef.current);
		savedValues ? setIsDirty(savedValues !== stringValue) : setIsDirty(!isEqual(stringFormRef, stringValue));
	}, [form]);

	return { isDirty, setIsDirty };
};

export { useShouldBeSaved };
