import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { MuiThemeProvider, createTheme } from '@material-ui/core/styles';
import { grey } from '@material-ui/core/colors';
import merge from 'lodash/merge';
import cloneDeep from 'lodash/cloneDeep';
import set from 'lodash/set';
import { getClient } from '../../Reducers/Configurator/Selectors';
import { getUrl } from '../../Utils/getUrl';

const darkTextColor = '#282828';

const defaultTheme = {
    // this has to be added, see: https://material-ui.com/style/typography/#migration-to-typography-v2
    typography: {
        useNextVariants: true,
        h1: {
            color: darkTextColor,
        },
        h2: {
            color: darkTextColor,
        },
        h3: {
            color: darkTextColor,
        },
        h4: {
            color: darkTextColor,
        },
        h5: {
            color: darkTextColor,
        },
        h6: {
            color: darkTextColor,
        },
        subtitle1: {
            color: darkTextColor,
        },
        subtitle2: {
            color: darkTextColor,
        },
        body1: {
            color: darkTextColor,
        },
        body2: {
            color: darkTextColor,
        },
        button: {
            color: darkTextColor,
        },
        caption: {
            color: darkTextColor,
        },
        overline: {
            color: darkTextColor,
        },
    },
    breakpoints: {
        values: {
            xs: 0,
            sm: 568, // iPhone 5 problematic (width = 568 < 600..)
            md: 960,
            lg: 1280,
            xl: 1920,
        },
    },
    // use this variables instead of directly writing the media query
    orientation: {
        landscape: '@media (orientation: landscape)',
        portrait: '@media (orientation: portrait)',
    },
    palette: {
        primary: {
            main: '#ffffff',
            darkText: darkTextColor,
            success: '#4fc36d',
            warning: '#ffb800',
            error: '#ed1C29',
        },
        secondary: {
            dark: '#212121',
            main: '#C8C8C8',
            light: '#76777A',
            lighter: '#C4C4C4',
        },
    },
    tapHighlightColor: 'transparent',
    overrides: {
        MuiFormLabel: {
            root: {
                '&$focused': {
                    color: '#C8C8C8',
                },
            },
        },
        MuiButton: {
            outlined: {
                color: darkTextColor,
            },
            root: {
                textAlign: 'left',
                textTransform: 'none',
            },
        },
        MuiIcon: {
            root: {
                color: darkTextColor,
            },
        },
        MuiOutlinedInput: {
            root: {
                color: darkTextColor,
                '&$focused': {
                    '& $notchedOutline': {
                        borderColor: '#C8C8C8',
                    },
                },
            },
        },
        Designer: {
            root: {
                margin: '20px',
            },
        },
        'Designer-Editor': {
            graphicsEditorContainer: {
                backgroundColor: 'transparent',
                backgroundImage: 'none',
                // Set overflow to visible to prevent scrollbars. Later when it comes to zooming,
                // a custom class might be added to set the overflow 'auto' again when canvas > container.
                overflow: 'visible',
                border: '1px solid gray',
            },
        },
        'Designer-CanvasContainer': {
            canvasContainer: {
                '& canvas': {
                    backgroundColor: 'rgba(255,255,255,0.5)',
                    //boxShadow: '0px 0px 0px 1px gray',
                    //border: '1px solid gray',
                    boxSizing: 'border-box',
                },
            },
        },
        'Designer-SelectionToolbox': {
            selectionToolboxContainer: {
                position: 'relative',
                top: 'auto',
            },
        },
        'Designer-TextTools': {
            textEditorContent: {
                border: 0,
                width: '100%',
                outline: 0,
                maxHeight: 22,
                overflowX: 'hidden',
                overflowY: 'auto',
                backgroundColor: 'transparent',
            },
        },
    },
    // custom part
    layout: {
        sidebar: {
            width: 350,
        },
    },
    buttons: {
        mainBtn: {
            backgroundColor: darkTextColor,
        },
        mainBtnHover: {
            backgroundColor: grey[700],
        },
    },
    smallScreen: {
        padding: '16px',
        centeredDialogPadding: '32px',
    },
    creator: {
        viewSelectBreakpoint: 1150,
        option: {
            image: {
                width: '100px',
            },
            textArea: {
                textWidth: '160px',
            },
        },
        productPart: {
            captionPaddingTop: '4px',
            itemSize: '110px',
            selectedItemSize: '118px',
            lineHeight: '1em',
            markerThickness: '8px',
        },
        productPartsList: {
            marginLeft: 10,
            marginBottom: '10px',
            markerVerticalPosition: 'right',
            paddingTop: 100,
        },
    },
    designer: {
        imageEditDialog: {
            errorColor: '#ff0000',
        },
    },
};

const loadClientFont = (fontName, url) => {
    let clientFont = document.createElement('style');
    clientFont.appendChild(
        document.createTextNode('@font-face { font-family: "' + fontName + '"; src: url("' + url + '"); }, ')
    );
    document.head.appendChild(clientFont);
};

const createThemeFromClientTheme = (clientTheme, customTheme) => {
    const theme = {};

    if (clientTheme.highlightColor) {
        set(theme, 'palette.primary.main', clientTheme.highlightColor);
        set(
            theme,
            'overrides.Designer-Editor.graphicsEditorContainer.borderColor',
            clientTheme.highlightColor
        );
    }
    if (clientTheme.font) {
        const fontUrl = getUrl(clientTheme.font);
        const fontName = clientTheme.font.substring(
            clientTheme.font.lastIndexOf('/') + 1,
            clientTheme.font.indexOf('.')
        );
        loadClientFont(fontName, fontUrl);
        set(theme, 'typography.fontFamily', fontName);
    }

    return merge(cloneDeep(defaultTheme), customTheme, theme);
};

const mapStateToProps = state => ({
    client: getClient(state.configurator),
});

export const ThemeMixer = ({ client, customTheme, withTheme, children }) => {
    const themeMix = useMemo(() => {
        const theme = createTheme(
            createThemeFromClientTheme(client && client.theme ? client.theme : {}, customTheme || {})
        );
        if (typeof withTheme === 'function') {
            withTheme(theme);
        }
        return theme;
    }, [client, customTheme, withTheme]);
    return <MuiThemeProvider theme={themeMix}>{children}</MuiThemeProvider>;
};

ThemeMixer.propTypes = {
    client: PropTypes.object,
    customTheme: PropTypes.object,
    withTheme: PropTypes.func,
    children: PropTypes.node,
};

ThemeMixer.defaultProps = {
    client: {},
    customTheme: {},
    withTheme: null,
};

export const ConnectedThemeProvider = connect(mapStateToProps)(ThemeMixer);

export default ConnectedThemeProvider;
