import { useCallback, useEffect, useMemo } from "react";
import { useForm, } from "react-hook-form";
import { useEditorContext } from "../context/editor-context.js";
import { useDefaultFormValues } from "./useDefaultFormValues.js";
function useWrappedForm(defaultValues) {
    const form = useForm({
        defaultValues: defaultValues,
    });
    return form;
}
export function useSubmit(props) {
    const { operation, tableName, tableItem } = props;
    const { handleAction, fixedIncomeTypes, spvs, accounts } = useEditorContext();
    const defaultValues = useDefaultFormValues({
        tableName,
        tableItem,
        fixedIncomeTypes,
        spvs,
        accounts,
    });
    const action = operation === "create" ? "CREATE" : "EDIT";
    const formValues = defaultValues;
    const { register, handleSubmit, reset, watch, control, formState } = useWrappedForm(formValues);
    useEffect(() => {
        reset(formValues);
    }, [formValues, reset]);
    const onSubmit = useCallback((payload) => {
        const actionType = `${action}_${tableName}`;
        handleAction({
            type: actionType,
            payload,
        });
    }, [action, handleAction, tableName]);
    const submit = handleSubmit(onSubmit);
    return useMemo(() => ({
        register,
        reset,
        watch,
        control,
        formState,
        submit,
    }), [control, formState, register, reset, submit, watch]);
}
//# sourceMappingURL=useSubmit.js.map