import { ComponentChild, createContext, render, type JSX, type RefObject } from "preact";
import Component from "../../components/component";
import { type default as NoteContextType } from "../../components/note_context";

export const ParentComponent = createContext<Component | null>(null);
export const NoteContext = createContext<NoteContextType | null>(null);

interface ComponentContext {
    parentComponent: Component | null;
    noteContext: NoteContextType | null;
}

/**
 * Takes in a React ref and returns a corresponding JQuery selector.
 *
 * @param ref the React ref from which to obtain the jQuery selector.
 * @returns the corresponding jQuery selector.
 */
export function refToJQuerySelector<T extends HTMLElement>(ref: RefObject<T> | null): JQuery<T> {
    if (ref?.current) {
        return $(ref.current);
    } else {
        return $();
    }
}

/**
 * Renders a React component and returns the corresponding DOM element wrapped in JQuery.
 *
 * @param parentComponent the parent Trilium component for the component to be able to handle events.
 * @param el the JSX element to render.
 * @returns the rendered wrapped DOM element.
 */
export function renderReactWidget(context: ComponentContext, el: JSX.Element) {
    return renderReactWidgetAtElement(context, el, new DocumentFragment()).children();
}

export function renderReactWidgetAtElement({ parentComponent, noteContext }: ComponentContext, el: JSX.Element, container: Element | DocumentFragment) {
    render((
        <ParentComponent.Provider value={parentComponent}>
            <NoteContext.Provider value={noteContext}>
                {el}
            </NoteContext.Provider>
        </ParentComponent.Provider>
    ), container);
    return $(container) as JQuery<HTMLElement>;
}

export function disposeReactWidget(container: Element) {
    render(null, container);
}

export function joinElements(components: ComponentChild[], separator = ", ") {
    return components.reduce<any>((acc, item) =>
        (acc.length ? [...acc, separator, item] : [item]), []);
}
