import { get, writable } from "svelte/store";
export const useForm = (options) => {
    const data = writable((options?.initialValues || {}));
    const errors = writable({});
    const handleChange = (key, sanitizeFn) => (e) => {
        const value = sanitizeFn?.(e.target.value) ?? e.target.value;
        options?.onChange?.(key, value);
        data.update(prv => ({ ...prv, [key]: value }));
    };
    const handleChangeValue = (key, sanitizeFn) => (e) => {
        const value = sanitizeFn?.(e) ?? e;
        options?.onChange?.(key, value);
        data.update(prv => ({ ...prv, [key]: value }));
    };
    const handleSubmit = (e) => {
        e.preventDefault();
        const validations = options?.validations;
        errors.set({});
        if (validations) {
            let valid = true;
            const newErrors = {};
            for (const key in validations) {
                const value = get(data)?.[key];
                const validation = validations[key];
                if (validation?.required?.value && !value) {
                    valid = false;
                    newErrors[key] = validation?.required?.message;
                }
                const pattern = validation?.pattern;
                if (pattern?.value && !RegExp(pattern.value).test(value)) {
                    valid = false;
                    newErrors[key] = pattern.message;
                }
                const custom = validation?.custom;
                if (custom?.isValid && !custom.isValid(value)) {
                    valid = false;
                    newErrors[key] = custom.message;
                }
            }
            if (!valid) {
                errors.set(newErrors);
                options?.onError?.();
                return;
            }
        }
        if (options?.onSubmit) {
            options.onSubmit();
        }
    };
    const handleClear = (e) => {
        e.preventDefault();
        data.set({});
        errors.set({});
    };
    return {
        data,
        errors,
        handleChange,
        handleChangeValue,
        handleSubmit,
        handleClear,
    };
};
