import mergeWith from 'lodash.mergewith';
import { createContext, useContext } from 'react';

import type { StitchesCSS } from '../../stitches.config';

export type FormValue = {
    layout: 'horizontal' | 'vertical';
    spacing: 'none' | 'setHeight';
    labelOptions: {
        width?: StitchesCSS['width'];
    };
};

/**
 * Form Context
 */
export const FormContext = createContext<FormValue | undefined>(undefined);

/**
 * Access the current Form's context
 *
 * @param values - current values
 *
 * @returns the FormValue
 */
export function useForm(values: Partial<FormValue>): FormValue {
    const context = useContext(FormContext);
    if (context === undefined) {
        throw new Error('useForm must be used within a Form');
    }

    // merge but ignore the undefined values
    const merged = mergeWith({}, context, values, (a, b) => {
        if (b === undefined) {
            return a;
        }
    });

    // merge the two options together with the values taking precence
    return merged;
}
