"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const useForm_1 = require("../../../useForm");
const constants_1 = require("../../constants");
const useLogic = ({ initialValue, children, validate, onClose, onSubmit, }) => {
    const getDefaultValues = () => {
        if (initialValue) {
            return initialValue;
        }
        if (typeof children === 'string' || typeof children === 'number') {
            return children;
        }
        return null;
    };
    const calculatedInitialValue = (0, react_1.useMemo)(() => getDefaultValues(), [initialValue, children]);
    const resolver = (formValues) => {
        const validatedValue = formValues[constants_1.FIELD_NAME];
        const validationResult = validate?.(validatedValue);
        if (!validationResult) {
            return {
                values: formValues,
                errors: {},
            };
        }
        return {
            values: {},
            errors: {
                [constants_1.FIELD_NAME]: {
                    message: validationResult?.message,
                    type: validationResult?.cause.code,
                },
            },
        };
    };
    const form = (0, useForm_1.useForm)({
        defaultValues: {
            [constants_1.FIELD_NAME]: calculatedInitialValue,
        },
        resolver: validate ? resolver : undefined,
    });
    const handleSubmit = (formValues) => {
        const fieldValue = formValues[constants_1.FIELD_NAME];
        const isValueChanged = fieldValue !== calculatedInitialValue;
        onClose();
        if (isValueChanged) {
            return onSubmit(fieldValue);
        }
    };
    return {
        formProps: {
            form,
            onSubmit: form.handleSubmit(handleSubmit),
        },
    };
};
exports.useLogic = useLogic;
