import DataTableContext from "@insite/mobius/DataTable/DataTableContext";
import applyPropBuilder from "@insite/mobius/utilities/applyPropBuilder";
import getColor from "@insite/mobius/utilities/getColor";
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, { css, withTheme } from "styled-components";

export type DataTableRowProps = MobiusStyledComponentProps<
    "tr",
    {
        /** CSS string or styled-components function to be injected into this component. */
        css?: StyledProp<DataTableRowProps>;
        evenRowCss?: StyledProp<DataTableRowProps>;
        /**
         * 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;
    }
>;

const DataTableRowStyle = styled.tr<DataTableRowProps>`
    background: ${getColor("common.background")};
    &:nth-child(even) {
        background: ${getColor("common.accent")};
        ${({ evenRowCss }) => evenRowCss}
    }
    ${injectCss}
`;

const DataTableRow: React.FC<DataTableRowProps> = ({ mergeCss, css: dataTableCss = "", ...otherProps }) => {
    const { applyStyledProp } = applyPropBuilder({ ...otherProps }, { component: "dataTable" });
    const { theme } = otherProps;
    const resolvedMergeCss = mergeCss ?? theme?.dataTable.defaultProps?.mergeCss;
    return (
        <DataTableContext.Consumer>
            {() => (
                <DataTableRowStyle
                    css={css`
                        ${applyStyledProp(["cssOverrides", "row"], resolvedMergeCss)}
                        ${dataTableCss}
                    `}
                    evenRowCss={applyStyledProp(["cssOverrides", "evenRow"], resolvedMergeCss)}
                    {...otherProps}
                />
            )}
        </DataTableContext.Consumer>
    );
};

export default withTheme(DataTableRow);
