import { useMemo } from 'react';
import { useForm } from '../../../useForm';
import { FIELD_NAME } from '../../constants';
export 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 = useMemo(() => getDefaultValues(), [initialValue, children]);
    const resolver = (formValues) => {
        const validatedValue = formValues[FIELD_NAME];
        const validationResult = validate?.(validatedValue);
        if (!validationResult) {
            return {
                values: formValues,
                errors: {},
            };
        }
        return {
            values: {},
            errors: {
                [FIELD_NAME]: {
                    message: validationResult?.message,
                    type: validationResult?.cause.code,
                },
            },
        };
    };
    const form = useForm({
        defaultValues: {
            [FIELD_NAME]: calculatedInitialValue,
        },
        resolver: validate ? resolver : undefined,
    });
    const handleSubmit = (formValues) => {
        const fieldValue = formValues[FIELD_NAME];
        const isValueChanged = fieldValue !== calculatedInitialValue;
        onClose();
        if (isValueChanged) {
            return onSubmit(fieldValue);
        }
    };
    return {
        formProps: {
            form,
            onSubmit: form.handleSubmit(handleSubmit),
        },
    };
};
