import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import MenuItem from '@material-ui/core/MenuItem';
import TextField from '@material-ui/core/TextField';
import CheckCircle from '@material-ui/icons/CheckCircle';
import Error from '@material-ui/icons/Error';
import Icon from '@material-ui/core/Icon';
import Modal from '@material-ui/core/Modal';
import withWidth from '@material-ui/core/withWidth';
import { t, translationExists } from 'Framework/i18n';
import AnalyticsWrapper from 'App/Shared/Components/Analytics/AnalyticsWrapper';
import InformationTag from 'App/Shared/Components/InformationTag/InformationTag';
import customClassName from 'App/Utils/customClassName';
import Select from '../Select';

const styles = theme => ({
    card: {
        [theme.breakpoints.down('xs')]: {
            zIndex: 1,
        },
    },
    cardBoxed: {
        borderTop: '7px solid ' + theme.palette.primary.main,
        overflow: 'inherit',
    },
    cardUnboxed: {
        borderTop: 'none',
        boxShadow: 'none',
        borderRadius: 0,
        pointerEvents: 'all',
    },
    cardContent: {
        padding: 10,

        [theme.breakpoints.down('xs')]: {
            paddingTop: 0,
            '&:last-child': {
                paddingBottom: 8,
            },
        },
    },
    cardContentRoot: {
        padding: '0 16px',
        [theme.breakpoints.down('xs')]: {
            padding: 0,
        },
        '&:last-child': {
            [theme.breakpoints.up('sm')]: {
                paddingBottom: 16,
            },
        },
    },
    listItemText: {
        fontSize: '12px',
        lineHeight: '40px',
        [theme.breakpoints.down('xs')]: {
            lineHeight: '56px',
        },
    },
    listItem: {
        display: 'flex',
        [theme.breakpoints.down('sm')]: {
            minWidth: 100,
        },
    },
    GridItemXS: {
        [theme.breakpoints.down('xs')]: {
            paddingRight: 15,
        },
    },
    GridContainer: {
        paddingTop: 9,
        [theme.breakpoints.down('xs')]: {
            paddingRight: 48,
            paddingTop: 0,
        },
    },
    arrowNone: {
        display: 'none',
    },
    outlinedInput: {
        fontSize: 15,
        height: 40,
        padding: '0 0 0 16px',
        cursor: 'default',
        lineHeight: '40px',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        [theme.breakpoints.down('xs')]: {
            height: 56,
            padding: 0,
        },
    },
    iconedItem: {
        [theme.breakpoints.down('xs')]: {
            paddingRight: '6px !important',
        },
    },
    underlineInputText: {
        marginBottom: 0,
        [theme.breakpoints.up('sm')]: {
            marginBottom: 8,
        },
        '&:before': {
            borderBottom: 0,
            [theme.breakpoints.up('sm')]: {
                borderBottom: '1px solid rgba(0, 0, 0, 0.42)',
            },
        },
        //https://github.com/mui-org/material-ui/issues/12192#issuecomment-406182809
        '&&&&:hover:before': {
            borderBottom: 0,
            [theme.breakpoints.up('sm')]: {
                borderBottom: '1px solid rgba(0, 0, 0, 0.42)',
            },
        },
        '&:after': {
            borderBottom: 0,
            [theme.breakpoints.up('sm')]: {
                borderBottom: '1px solid transparent',
            },
        },
    },
    iconRootCheck: {
        position: 'absolute',
        right: 30,
        height: 40,
        lineHeight: '40px',
        [theme.breakpoints.down('xs')]: {
            position: 'unset',
            paddingRight: 18,
            height: 56,
            lineHeight: '56px',
        },
    },
    colorAmountMessage: {
        display: 'inline-flex',
        backgroundColor: '#4FC36D',
        marginTop: 16,
        borderRadius: '4px',
        minHeight: 40,
        color: '#fff',
        padding: '10px 16px',
        [theme.breakpoints.down('xs')]: {
            minHeight: 56,
            position: 'absolute',
            margin: 0,
            right: 0,
        },
    },
    colorAmountMessageText: {
        verticalAlign: 'middle',
        color: '#fff',
        padding: '0 10px',
        fontSize: 15,
        fontWeight: 500,

        [theme.breakpoints.down('xs')]: {
            display: 'none',

            '.colorAmountMessageOpen &': {
                display: 'inline',
                lineHeight: '40px',
            },
        },
    },
    colorAmountMessageWarning: {
        backgroundColor: '#ED1C29',
    },
    colorAmountMessageIcon: {
        marginTop: '-2px',
        [theme.breakpoints.down('xs')]: {
            marginTop: 8,
        },
    },
    alignInfoButton: {
        display: 'flex',
        '& .info-btn': {
            '& button': {
                '@media (min-width: 320px) and (max-width: 480px)': {
                    padding: '12px 0',
                },
            },
        },
    },
});

class DesignAreaControlbox extends React.Component {
    static propTypes = {
        boxed: PropTypes.bool,
        classes: PropTypes.object,
        valueProductionMethod: PropTypes.object,
        valueDesignArea: PropTypes.object,
        colorAmount: PropTypes.number,
        maxColorAmount: PropTypes.number,
        hasAmountIndicatorWarning: PropTypes.bool,
        colorDisabled: PropTypes.bool,
        handleChangeProductionMethod: PropTypes.func,
        handleChangeDesignArea: PropTypes.func,
        handleChangePrintingColor: PropTypes.func,
        designAreas: PropTypes.array,
        designedAreas: PropTypes.object,
        width: PropTypes.string,
    };

    constructor(props) {
        super(props);

        this.state = {
            amountIndicatorOpen: false,
        };
    }

    openAmountIndicatorModal = () => {
        this.setState({ amountIndicatorOpen: true });
    };

    closeAmountIndicatorModal = () => {
        this.setState({ amountIndicatorOpen: false });
    };

    getColorAmountMessageClass = () => {
        const { classes, hasAmountIndicatorWarning } = this.props;
        const { amountIndicatorOpen } = this.state;

        let className = `${classes.GridItemXS} ${classes.colorAmountMessage}`;

        if (hasAmountIndicatorWarning) {
            className += ` ${classes.colorAmountMessageWarning}`;
        }

        if (amountIndicatorOpen) {
            className += ' colorAmountMessageOpen';
        }

        return className;
    };

    getColorAmountMessage = () => {
        const { colorAmount, maxColorAmount } = this.props;

        if (!maxColorAmount) {
            return t('colorAmountIndicator.unlimitedColors');
        }

        if (colorAmount > maxColorAmount) {
            return t('colorAmountIndicator.warning', { colorAmount, maxColorAmount });
        }

        return t('colorAmountIndicator.ok', { colorAmount });
    };

    render() {
        const {
            classes,
            boxed,
            handleChangeDesignArea,
            handleChangeProductionMethod,
            valueProductionMethod,
            valueDesignArea,
            designAreas,
            designedAreas,
            width,
            colorDisabled,
            hasAmountIndicatorWarning,
        } = this.props;
        const { amountIndicatorOpen } = this.state;
        if (!valueDesignArea || !valueProductionMethod) {
            return null;
        }

        const { designProductionMethods } = valueDesignArea;
        return (
            <Card
                className={clsx(
                    classes.card,
                    boxed ? classes.cardBoxed : classes.cardUnboxed,
                    customClassName('design-area-box')
                )}
            >
                <CardContent
                    className={boxed ? '' : classes.cardContent}
                    classes={{ root: classes.cardContentRoot }}
                >
                    <Grid container className={classes.GridContainer}>
                        <Grid
                            item
                            xs={6}
                            sm={12}
                            md={12}
                            lg={12}
                            className={
                                classes.GridItemXS +
                                (translationExists('designAreaInformation')
                                    ? ' ' + classes.alignInfoButton
                                    : '')
                            }
                        >
                            {designAreas.length > 1 ? (
                                <React.Fragment>
                                    <AnalyticsWrapper targetId="design_area_switch">
                                        <Select
                                            bold
                                            value={valueDesignArea.identifier}
                                            onChange={handleChangeDesignArea}
                                            readOnly={false}
                                            iconClass={''}
                                            autoWidth={width === 'xs'}
                                        >
                                            {designAreas.map(area => (
                                                <MenuItem
                                                    key={area.identifier}
                                                    value={area.identifier}
                                                    aria-label={area.title}
                                                >
                                                    <div className={classes.listItem}>
                                                        <Typography
                                                            className={
                                                                classes.listItemText +
                                                                ' ' +
                                                                (designedAreas[area.identifier]
                                                                    ? classes.iconedItem
                                                                    : '')
                                                            }
                                                            noWrap
                                                        >
                                                            {area.title}
                                                        </Typography>
                                                        {designedAreas[area.identifier] && (
                                                            <Icon className={classes.iconRootCheck}>
                                                                check_circle_outline
                                                            </Icon>
                                                        )}
                                                    </div>
                                                </MenuItem>
                                            ))}
                                        </Select>
                                    </AnalyticsWrapper>
                                    {translationExists('designAreaInformation') && (
                                        <div className="info-btn">
                                            <InformationTag infoText={t('designAreaInformation')} />
                                        </div>
                                    )}
                                </React.Fragment>
                            ) : (
                                designAreas.map(area => (
                                    <TextField
                                        key={area.identifier}
                                        readOnly
                                        inputProps={{ readOnly: true }}
                                        fullWidth={true}
                                        value={area.title}
                                        translate="no"
                                        InputProps={{
                                            classes: {
                                                input: classes.outlinedInput,
                                                underline: classes.underlineInputText,
                                            },
                                        }}
                                    />
                                ))
                            )}
                        </Grid>

                        {designProductionMethods && (
                            <Grid
                                item
                                xs={6}
                                sm={12}
                                md={12}
                                lg={12}
                                className={
                                    classes.GridItemXS +
                                    (translationExists('designProductionInformation')
                                        ? ' ' + classes.alignInfoButton
                                        : '')
                                }
                            >
                                {designProductionMethods.length > 1 ? (
                                    <React.Fragment>
                                        <AnalyticsWrapper
                                            targetId="design_production_switch"
                                            data={valueProductionMethod.identifier}
                                        >
                                            <Select
                                                bold
                                                value={valueProductionMethod.identifier}
                                                onChange={handleChangeProductionMethod}
                                                readOnly={false}
                                                iconClass={''}
                                            >
                                                {designProductionMethods.map(productionMethod => (
                                                    <MenuItem
                                                        key={productionMethod.identifier}
                                                        value={productionMethod.identifier}
                                                        aria-label={productionMethod.title}
                                                    >
                                                        {' '}
                                                        <Typography className={classes.listItemText} noWrap>
                                                            {productionMethod.title}
                                                        </Typography>
                                                    </MenuItem>
                                                ))}
                                            </Select>
                                        </AnalyticsWrapper>
                                        {translationExists('designProductionInformation') && (
                                            <div className="info-btn">
                                                <InformationTag infoText={t('designProductionInformation')} />
                                            </div>
                                        )}
                                    </React.Fragment>
                                ) : (
                                    designProductionMethods.map(productionMethod => (
                                        <TextField
                                            key={productionMethod.identifier}
                                            readOnly
                                            inputProps={{ readOnly: true }}
                                            fullWidth={true}
                                            value={productionMethod.title}
                                            translate="no"
                                            InputProps={{
                                                classes: {
                                                    input: classes.outlinedInput,
                                                    underline: classes.underlineInputText,
                                                },
                                            }}
                                        />
                                    ))
                                )}
                            </Grid>
                        )}
                        {!colorDisabled && (
                            <Grid
                                item
                                xs={12}
                                sm={12}
                                md={12}
                                lg={12}
                                className={this.getColorAmountMessageClass()}
                                onClick={this.openAmountIndicatorModal}
                            >
                                {hasAmountIndicatorWarning ? (
                                    <Error className={classes.colorAmountMessageIcon} />
                                ) : (
                                    <CheckCircle className={classes.colorAmountMessageIcon} />
                                )}
                                <Typography
                                    variant="body1"
                                    component="span"
                                    className={classes.colorAmountMessageText}
                                >
                                    {this.getColorAmountMessage()}
                                </Typography>
                            </Grid>
                        )}
                        <Modal
                            open={width === 'xs' && amountIndicatorOpen}
                            BackdropProps={{ invisible: true }}
                            onClick={this.closeAmountIndicatorModal}
                        >
                            <div />
                        </Modal>
                    </Grid>
                </CardContent>
            </Card>
        );
    }
}

export default withWidth({ initialWidth: 'lg' })(
    withStyles(styles, { name: 'DesignAreaControlbox' })(DesignAreaControlbox)
);
