import ContentMode from "@insite/client-framework/Common/ContentMode";
import { getCurrentPage } from "@insite/client-framework/Store/Data/Pages/PageSelectors";
import AxiomIcon from "@insite/shell/Components/Icons/AxiomIcon";
import ClickerStyle from "@insite/shell/Components/Shell/ClickerStyle";
import shellTheme from "@insite/shell/ShellTheme";
import { setContentMode } from "@insite/shell/Store/ShellContext/ShellContextActionCreators";
import ShellState from "@insite/shell/Store/ShellState";
import { TS } from "@insite/shell/TS";
import * as React from "react";
import { connect, ResolveThunks } from "react-redux";

const mapStateToProps = (state: ShellState, ownProps: OwnProps) => ({
    targetMatchesCurrentContentMode: state.shellContext.contentMode === ownProps.targetContentMode,
    neverPublished: state.pageTree.neverPublishedNodeIds[getCurrentPage(state).nodeId],
});

const mapDispatchToProps = {
    setContentMode,
};

type OwnProps = { targetContentMode: ContentMode; icon: string; disabled?: boolean };

type Props = ReturnType<typeof mapStateToProps> & ResolveThunks<typeof mapDispatchToProps> & OwnProps;

class ContentModeClicker extends React.Component<Props> {
    readonly contentModeLabel: Record<ContentMode, string> = {
        Editing: TS("Edit"),
        Previewing: TS("Preview"),
        Viewing: TS("View"),
    };

    onClick = () => {
        const { targetMatchesCurrentContentMode, setContentMode, targetContentMode, neverPublished } = this.props;
        setContentMode(targetMatchesCurrentContentMode ? (neverPublished ? "Editing" : "Viewing") : targetContentMode);
    };

    render() {
        const { targetMatchesCurrentContentMode, icon, targetContentMode, disabled } = this.props;
        const {
            colors: { common, text },
        } = shellTheme;
        let iconColor: string;
        if (disabled) {
            iconColor = common.disabled;
        } else {
            iconColor = text.main;
        }

        return (
            <ClickerStyle
                active={targetMatchesCurrentContentMode}
                clickable
                onClick={this.onClick}
                data-test-selector={`contentModeClicker_${targetContentMode}`}
                disabled={disabled}
                title={this.contentModeLabel[targetContentMode]}
            >
                <AxiomIcon src={icon} color={iconColor} size={20} />
            </ClickerStyle>
        );
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ContentModeClicker);
