import LayoutGroupContext, { LayoutGroupContextData } from "@insite/mobius/LayoutGroup/LayoutGroupContext";
import { applyPropBuilder } from "@insite/mobius/utilities";
import { StyledProp } from "@insite/mobius/utilities/InjectableCss";
import injectCss from "@insite/mobius/utilities/injectCss";
import MobiusStyledComponentProps from "@insite/mobius/utilities/MobiusStyledComponentProps";
import * as React from "react";
import styled, { withTheme } from "styled-components";

export interface LayoutGroupPresentationProps {
    /** CSS string or styled-components function to be injected into this component. */
    css?: StyledProp<LayoutGroupProps>;
    /**
     * Indicates how the `css` property is combined with the default `css` property from the theme.
     * If true, the default css is applied first and then the component css is applied after causing
     * a merge, much like normal CSS. If false, only the component css is applied, overriding the default css in the theme.
     */
    mergeCss?: boolean;
}

export type LayoutGroupProps = MobiusStyledComponentProps<
    "div",
    LayoutGroupContextData &
        LayoutGroupPresentationProps & {
            children?: React.ReactNode;
        }
>;

const LayoutGroupStyle = styled.div<LayoutGroupProps>`
    ${injectCss}
`;

/**
 * LayoutTable equivalent to a `<tr>` in an HTML table, but LayoutGroups can also be arranged as columns.
 */
const LayoutGroup: React.FC<LayoutGroupProps> = ({ children, groupIndex, mergeCss, css, ...otherProps }) => {
    const { applyStyledProp } = applyPropBuilder({ css, ...otherProps }, { component: "layoutGroup" });
    const { theme } = otherProps;
    const resolvedMergeCss = mergeCss ?? theme?.layoutGroup.defaultProps?.mergeCss;
    return (
        <LayoutGroupContext.Provider value={{ groupIndex }}>
            <LayoutGroupStyle groupIndex={groupIndex} css={applyStyledProp("css", resolvedMergeCss)}>
                {children}
            </LayoutGroupStyle>
        </LayoutGroupContext.Provider>
    );
};

/** @component */
export default withTheme(LayoutGroup);

export { LayoutGroupStyle };
