import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Switch from '@material-ui/core/Switch';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Typography from '@material-ui/core/Typography';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import Divider from '@material-ui/core/Divider';
import { grey } from '@material-ui/core/colors';
import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import { t, translationExists } from 'Framework/i18n';
import AmountInput from 'App/Shared/Components/AmountInput';
import MainButton from 'Shared/Components/MainButton';
import AnalyticsWrapper from 'App/Shared/Components/Analytics/AnalyticsWrapper';
import InformationTag from 'App/Shared/Components/InformationTag/InformationTag';
import TextField from '@material-ui/core/TextField';
import Input from '@material-ui/core/Input';
import Checkbox from '@material-ui/core/Checkbox';
import { combineMediaQueriesWithAnd } from '../../../../../Utils/Styles/combineMediaQueries';

export const styles = theme => {
    const orientation = {
        portrait: '',
        ...theme.orientation,
    };
    return {
        Card: {
            borderTop: '7px solid ' + theme.palette.primary.main,
        },
        Container: {
            border: '1px solid',
            borderColor: '',
        },
        ContainerItem: {
            paddingTop: '5px',
        },
        SelectItems: {
            border: '1px solid',
        },
        DesignAreaContainer: {
            background: grey[300],
            height: '50%',
            borderColor: grey[400],
            borderTop: '1px solid',
            borderBottom: '1px solid',
            padding: '15px',
        },
        AmountContainer: {
            marginTop: '15px',
            display: 'flex',
            justifyContent: 'center',
        },
        DividerAmount: {
            marginTop: '15px',
            marginLeft: '20px',
            marginRight: '20px',
        },
        CalculationWidgetBtn: {
            fontWeight: 'bold',
            marginLeft: '25px',
            textTransform: 'none',
        },
        ExpansionPanel: {
            borderColor: grey[450],
            border: '1px solid',
            width: '100%',
            minWidth: 150,
        },
        gridItemExpansionPanel: {
            height: 40,
            [combineMediaQueriesWithAnd(orientation.portrait, '@media (max-width: 345px)')]: {
                '& label': {
                    marginRight: 0,
                },
            },
        },
        footerButton: {
            [combineMediaQueriesWithAnd(orientation.portrait, '@media (max-width: 360px)')]: {
                width: '100%',
                margin: '0px 0px 10px',
                padding: '0 24px',
                '& button': {
                    width: '100%',
                    marginLeft: 0,
                },
            },
        },
        footerButtonsContainer: {
            width: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
        },
        ExpansionPanelSummary: {
            margin: 0,
            height: 44,
        },
        ExpansionPanelSummaryRoot: {
            minHeight: 44,
            paddingLeft: 12,
            paddingRight: 12,
        },
        ExpansionPanelSummaryExpanded: {
            margin: '0 !important',
            minHeight: '44px !important',
        },
        ExpansionDetailsRoot: {
            padding: '0px 24px 2px',
            [combineMediaQueriesWithAnd(orientation.portrait, '@media (max-width: 325px)')]: {
                padding: '0px 10px 2px',
            },
        },
        Typography: {
            fontWeight: 'bold',
            paddingLeft: '16px',
            height: '50px',
            paddingTop: '16px',
        },
        CardContentRoot: {
            padding: '0',
        },
        PriceListContainer: {
            padding: '25px',
        },
        colorSwitchBase: {
            color: grey[100],
            '&$colorChecked': {
                color: grey[900],
                '& + $colorBar': {
                    backgroundColor: grey[500],
                },
            },
        },
        colorBar: {},
        colorChecked: {},
        SelectLabel: {
            top: '25px',
            left: '5px',
        },
        technicalContainer: {
            minHeight: 220,
        },
        SaveConfigButton: {
            textTransform: 'none',
            whiteSpace: 'nowrap',
            margin: 0,
            padding: '6px 15px',
        },
        alignInfoButton: {
            display: 'flex',
            alignItems: 'center',
        },
        gridItemWrapper: {
            padding: '10px 10px 0px',
            overflow: 'hidden',
            flexGrow: 1,
            '& input': {
                textOverflow: 'ellipsis',
            },
        },
        gridItemAlignment: {
            textAlign: 'end',
            paddingRight: '24px',
        },
        formControl: {
            width: '100%',
            marginBottom: 8,
        },
        underlineInputText: {
            marginBottom: 8,
            //https://github.com/mui-org/material-ui/issues/12192#issuecomment-406182809
            '&&&&:hover:before': {
                borderBottom: '1px solid rgba(0, 0, 0, 0.42)',
            },
            '&:after': {
                borderBottom: '1px solid transparent',
            },
        },
        outlinedInput: {
            cursor: 'default',
        },
        underlineMenuItem: {
            '&:after': {
                borderBottom: '2px solid ' + theme.palette.primary.main,
            },
        },
        imageControlCheckbox: {
            padding: 15,
        },
    };
};

class CalculationWidget extends React.Component {
    static propTypes = {
        classes: PropTypes.object,
        designAreas: PropTypes.array,
        amountValue: PropTypes.number,
        amountError: PropTypes.bool,
        onChangeAmount: PropTypes.func,
        priceListComponent: PropTypes.object,
        designProductionMethods: PropTypes.array,
        currentDesignProductionMethod: PropTypes.object,
        colorAmounts: PropTypes.object,
        colorAmountList: PropTypes.array,
        handleChangeDesignProductionMethod: PropTypes.func,
        handleChangeSelectedColorAmount: PropTypes.func,
        onClickSaveConfiguration: PropTypes.func,
        onClickPrintConfiguration: PropTypes.func,
        loaderComponent: PropTypes.object,
        isSaveButtonEnabled: PropTypes.bool,
        notificationComponent: PropTypes.array,
        activeDesignAreas: PropTypes.object,
        toggleDesignArea: PropTypes.func,
        addPlaceholderImage: PropTypes.func,
        handleChangeDesignArea: PropTypes.func,
        defaultDesignArea: PropTypes.string,
        handlePreSelectDesignArea: PropTypes.func,
    };
    static defaultProps = {
        currentDesignProductionMethod: {},
        activeDesignAreas: {},
        colorAmounts: {},
        defaultDesignArea: {},
    };

    state = {
        expanded: null,
        addImages: false,
    };

    handleDesignAreaToggle = designAreaIdentifier => ({ target: { checked } }) => {
        const { toggleDesignArea, addPlaceholderImage } = this.props;
        toggleDesignArea && toggleDesignArea(designAreaIdentifier, checked);
        if (this.state.expanded !== designAreaIdentifier) {
            this.setState({
                expanded: designAreaIdentifier,
            });
        }
        if (this.state.addImages) {
            addPlaceholderImage && addPlaceholderImage(checked, [designAreaIdentifier]);
        }
    };

    handleAddingPlaceHolderImage = () => ({ target: { checked } }) => {
        const { addPlaceholderImage } = this.props;
        addPlaceholderImage && addPlaceholderImage(checked);
        this.setState({
            addImages: checked,
        });
    };

    onChangeDesignProductionMethod = () => ({ target: { value } }) => {
        const { handleChangeDesignProductionMethod } = this.props;
        handleChangeDesignProductionMethod && handleChangeDesignProductionMethod(value);
    };

    onChangeSelectedColorAmount = designAreaIdentifier => ({ target: { value } }) => {
        const { handleChangeSelectedColorAmount } = this.props;
        handleChangeSelectedColorAmount && handleChangeSelectedColorAmount(designAreaIdentifier, value);
    };

    handlePanelChange = panel => (event, expanded) => {
        this.setState({
            expanded: expanded ? panel : false,
        });
        const { handleChangeDesignArea } = this.props;
        handleChangeDesignArea && handleChangeDesignArea(panel);
    };

    preventPanelSwitch = evt => evt.stopPropagation();

    renderDesignProductionMethodSelect = () => {
        const { currentDesignProductionMethod, designProductionMethods, classes } = this.props;

        return (
            <Grid
                item
                className={
                    translationExists('designProductionInformation') ? ' ' + classes.alignInfoButton : ''
                }
                classes={{ root: classes.gridItemWrapper }}
            >
                <FormControl className={classes.formControl}>
                    <AnalyticsWrapper
                        targetId="widget_change_design_production_method"
                        data={currentDesignProductionMethod.identifier || ''}
                    >
                        <Select
                            value={currentDesignProductionMethod.identifier || ''}
                            onChange={this.onChangeDesignProductionMethod(currentDesignProductionMethod)}
                            input={<Input classes={{ underline: classes.underlineMenuItem }} />}
                        >
                            {designProductionMethods.map(designProductionMethod => (
                                <MenuItem
                                    key={designProductionMethod.identifier}
                                    value={designProductionMethod.identifier}
                                >
                                    {designProductionMethod.name}
                                </MenuItem>
                            ))}
                        </Select>
                    </AnalyticsWrapper>
                </FormControl>
                {translationExists('designProductionInformation') && (
                    <InformationTag infoText={t('designProductionInformation')} />
                )}
            </Grid>
        );
    };

    renderDesignProductionMethodValue = () => {
        const { designProductionMethods, classes } = this.props;
        return (
            <Grid item classes={{ root: classes.gridItemWrapper }}>
                {designProductionMethods.map(designProductionMethod => (
                    <TextField
                        key={designProductionMethod.identifier}
                        readOnly
                        inputProps={{ readOnly: true }}
                        fullWidth={true}
                        value={designProductionMethod.title}
                        InputProps={{
                            classes: {
                                input: classes.outlinedInput,
                                underline: classes.underlineInputText,
                            },
                        }}
                    />
                ))}
            </Grid>
        );
    };

    renderColorAmountValue = () => {
        const { classes, colorAmountList } = this.props;
        return (
            <Grid item classes={{ root: classes.gridItemWrapper }}>
                {colorAmountList.map(color => (
                    <TextField
                        key={color.identifier}
                        readOnly
                        inputProps={{ readOnly: true }}
                        fullWidth={true}
                        value={color.name || 1 + ' ' + t('designAreaControlbox.color')}
                        InputProps={{
                            classes: {
                                input: classes.outlinedInput,
                                underline: classes.underlineInputText,
                            },
                        }}
                    />
                ))}
            </Grid>
        );
    };

    renderColorAmountSelect = designArea => {
        const { classes, colorAmounts, colorAmountList } = this.props;
        return (
            <Grid
                item
                className={translationExists('colorAmountInformation') ? ' ' + classes.alignInfoButton : ''}
                classes={{ root: classes.gridItemWrapper }}
            >
                <FormControl className={classes.formControl}>
                    <Select
                        value={colorAmounts[designArea.identifier] || 1}
                        onChange={this.onChangeSelectedColorAmount(designArea.identifier)}
                        input={<Input classes={{ underline: classes.underlineMenuItem }} />}
                    >
                        {colorAmountList.map(colorAmount => (
                            <MenuItem key={colorAmount.identifier} value={colorAmount.identifier}>
                                {colorAmount.name}
                            </MenuItem>
                        ))}
                    </Select>
                </FormControl>
                {translationExists('colorAmountInformation') && (
                    <InformationTag infoText={t('colorAmountInformation')} />
                )}
            </Grid>
        );
    };

    render() {
        const {
            classes,
            designAreas,
            amountValue,
            amountError,
            onChangeAmount,
            priceListComponent,
            designProductionMethods,
            colorAmountList,
            onClickSaveConfiguration,
            onClickPrintConfiguration,
            loaderComponent,
            isSaveButtonEnabled,
            notificationComponent,
            activeDesignAreas,
        } = this.props;
        const { expanded, addImages } = this.state;

        return (
            <div>
                <Card className={classes.Card}>
                    <CardContent classes={{ root: classes.CardContentRoot }}>
                        {loaderComponent}
                        <Grid>
                            <Typography className={classes.Typography} variant="h6">
                                {t('calculationWidget.designCalculation')}
                            </Typography>
                        </Grid>
                        <div className={classes.DesignAreaContainer}>
                            <Typography variant="body2">
                                {t('calculationWidget.selectDesignAreaInfo')}
                            </Typography>

                            {designAreas.map(designArea => (
                                <Grid
                                    key={designArea.identifier}
                                    className={
                                        classes.ContainerItem +
                                        (translationExists('designAreaInformation')
                                            ? ' ' + classes.alignInfoButton
                                            : '')
                                    }
                                >
                                    <ExpansionPanel
                                        className={classes.ExpansionPanel}
                                        expanded={expanded === designArea.identifier}
                                        onChange={this.handlePanelChange(designArea.identifier)}
                                    >
                                        <ExpansionPanelSummary
                                            expandIcon={<ExpandMoreIcon />}
                                            classes={{
                                                content: classes.ExpansionPanelSummary,
                                                root: classes.ExpansionPanelSummaryRoot,
                                                expanded: classes.ExpansionPanelSummaryExpanded,
                                            }}
                                        >
                                            <Grid item xs={12} className={classes.gridItemExpansionPanel}>
                                                <FormControlLabel
                                                    control={
                                                        <Switch
                                                            classes={{
                                                                switchBase: classes.colorSwitchBase,
                                                                checked: classes.colorChecked,
                                                                track: classes.colorBar,
                                                            }}
                                                            onChange={this.handleDesignAreaToggle(
                                                                designArea.identifier
                                                            )}
                                                            onClick={this.preventPanelSwitch}
                                                            checked={activeDesignAreas[designArea.identifier]}
                                                        />
                                                    }
                                                    label={designArea.name}
                                                />
                                            </Grid>
                                        </ExpansionPanelSummary>
                                        <ExpansionPanelDetails
                                            classes={{
                                                root: classes.ExpansionDetailsRoot,
                                            }}
                                        >
                                            <Grid container>
                                                {designProductionMethods.length > 1
                                                    ? this.renderDesignProductionMethodSelect()
                                                    : this.renderDesignProductionMethodValue()}
                                                {colorAmountList.length > 1
                                                    ? this.renderColorAmountSelect(designArea)
                                                    : this.renderColorAmountValue(designArea)}
                                            </Grid>
                                        </ExpansionPanelDetails>
                                    </ExpansionPanel>
                                    {translationExists('designAreaInformation') && (
                                        <InformationTag infoText={t('designAreaInformation')} />
                                    )}
                                </Grid>
                            ))}
                        </div>
                        <div className={classes.imageControlCheckbox}>
                            <FormControlLabel
                                control={
                                    <Checkbox
                                        checked={addImages}
                                        onChange={this.handleAddingPlaceHolderImage()}
                                        color="primary"
                                    />
                                }
                                label={t('calculationWidget.addImage')}
                            />
                        </div>
                        <div className={classes.AmountContainer}>
                            <AnalyticsWrapper targetId="widget_change_amount" data={amountValue}>
                                <AmountInput
                                    onChange={onChangeAmount}
                                    value={amountValue}
                                    amountLabel={t('calculationWidget.amount')}
                                    error={amountError}
                                    onChangeDebounceWait={400}
                                />
                            </AnalyticsWrapper>
                        </div>

                        <Divider className={classes.DividerAmount} />

                        <div className={classes.technicalContainer}>
                            {notificationComponent}

                            <Grid className={classes.PriceListContainer}>
                                <Grid item>{priceListComponent}</Grid>
                            </Grid>
                        </div>

                        <Grid container classes={{ root: classes.footerButtonsContainer }}>
                            <Grid item classes={{ root: classes.footerButton }}>
                                <AnalyticsWrapper targetId="widget_print_view">
                                    <Button
                                        onClick={onClickPrintConfiguration}
                                        className={classes.CalculationWidgetBtn}
                                        variant="outlined"
                                        size="large"
                                    >
                                        {t('calculationWidget.printButtonText')}
                                    </Button>
                                </AnalyticsWrapper>
                            </Grid>
                            <Grid
                                item
                                classes={{ root: clsx(classes.gridItemAlignment, classes.footerButton) }}
                            >
                                <AnalyticsWrapper targetId="widget_open_configurator">
                                    <MainButton
                                        disabled={!isSaveButtonEnabled}
                                        onClick={onClickSaveConfiguration}
                                        className={classes.SaveConfigButton}
                                        variant="outlined"
                                        size="large"
                                    >
                                        {t('calculationWidget.openConfiguratorButtonText')}
                                    </MainButton>
                                </AnalyticsWrapper>
                            </Grid>
                        </Grid>
                    </CardContent>
                </Card>
            </div>
        );
    }
}

export default withStyles(styles, { name: 'CalculationWidget' })(CalculationWidget);
