import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import { t } from 'Framework/i18n';
import withWidth from '@material-ui/core/withWidth';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';
import Typography from '@material-ui/core/Typography';
import CheckCircle from '@material-ui/icons/CheckCircle';
import FileCopy from '@material-ui/icons/FileCopy';
import Error from '@material-ui/icons/Error';
import MainButton from 'Shared/Components/MainButton';
import CustomDialog from 'Shared/Components/CustomDialog';
import PropTypes from 'prop-types';
import Tooltip from '@material-ui/core/Tooltip';
import AccessibleButton from '../AccessibleButton/AccessibleButton';

const styles = theme => ({
    dialogTitleRoot: {
        padding: '12px 12px 20px',
        fontSize: '1.5rem',
        fontWeight: 400,
    },
    dialogContentRoot: {
        padding: '0 24px 0 12px',
    },
    saveconfigurationDialog: {
        borderTop: '7px solid ' + theme.palette.primary.main,
    },
    activeButton: {
        padding: '6px 15px',
    },
    saveConfigurationCode: {
        textAlign: 'center',
        marginTop: 24,
        marginBottom: 48,
        height: 40,
        fontSize: 24,
        lineHeight: '28px',
        [theme.breakpoints.down('xs')]: {
            height: 56,
            marginBottom: 32,
        },
    },
    TypographyCaption: {
        fontSize: 12,
        lineHeight: 1.7,
    },
    successResult: {
        background: '#4FC36D',
        color: '#fff',
        padding: '14px 8px',
        borderRadius: '4px',
    },
    successResultIcon: {
        float: 'left',
    },
    copyShareUrlIcon: {
        float: 'right',
        '&:hover': {
            color: 'rgba(0,0,0, 0.5)',
            cursor: 'pointer',
        },
    },
    errorResult: {
        background: '#ED1C29',
        color: '#fff',
        padding: '14px 8px',
        borderRadius: '4px',
        fontSize: 14,
        lineHeight: 1.7,
        textAlign: 'center',
    },
    errorResultIcon: {
        float: 'left',
    },
    dialogSavingInProgress: {
        flex: 1,
        alignItems: 'center',
        flexDirection: 'column',
        display: 'flex',
        height: 50,
        marginTop: 24,
    },
});

class SaveConfiguration extends React.Component {
    static propTypes = {
        classes: PropTypes.object,
        workInProgress: PropTypes.bool,
        errorMessage: PropTypes.string,
        code: PropTypes.string,
        loadLoginInfoInProgress: PropTypes.bool,
        show: PropTypes.bool,
        onClose: PropTypes.func,
        onOkClick: PropTypes.func,
        ProgressComponent: PropTypes.object,
        shareUrl: PropTypes.string,
        IconCopyShareUrl: PropTypes.elementType,
    };
    static defaultProps = {
        IconCopyShareUrl: FileCopy,
    };
    onCopyShareUrl = async shareUrl => {
        try {
            await navigator.clipboard.writeText(shareUrl);
        } catch (err) {
            // eslint-disable-next-line no-console
            console.error('Error while using the clipboard api:', err);
            // clipboard api only available in secure contexts (localhost, htttps) and modern(ish) browsers
            const textArea = document.createElement('textarea');
            textArea.textContent = shareUrl;
            textArea.style.position = 'fixed'; //avoid scrolling to bottom
            document.body.appendChild(textArea);
            const selection = document.getSelection();
            const range = document.createRange();
            range.selectNode(textArea);
            selection.removeAllRanges();
            selection.addRange(range);
            try {
                document.execCommand('copy');
            } catch (err) {
                // eslint-disable-next-line no-console
                console.log('Configuration link could not be copied: ', err);
            } finally {
                selection.removeAllRanges();
                document.body.removeChild(textArea);
            }
        }
    };

    render() {
        const {
            classes,
            workInProgress,
            errorMessage,
            code,
            loadLoginInfoInProgress,
            show,
            onClose,
            onOkClick,
            ProgressComponent,
            shareUrl,
            IconCopyShareUrl,
        } = this.props;

        return (
            <CustomDialog
                open={show}
                onClose={onClose}
                onCancel={onClose}
                dialogTitle={t('saveConfiguration.dialogTitle')}
            >
                <DialogContent className={classes.dialogContentRoot}>
                    {workInProgress && (
                        <div className={classes.dialogSavingInProgress}>
                            <ProgressComponent />
                        </div>
                    )}
                    {errorMessage && (
                        <Typography
                            variant="body1"
                            classes={{
                                root: classes.TypographyCaption,
                            }}
                            id="alert-dialog-description"
                        >
                            <div className={classes.errorResult}>
                                <Error className={classes.errorResultIcon} />
                                {t(errorMessage)}
                            </div>
                        </Typography>
                    )}
                    {!workInProgress && code && (
                        <React.Fragment>
                            <Typography
                                variant="body1"
                                classes={{ root: classes.TypographyCaption }}
                                id="alert-dialog-description"
                            >
                                {t('saveConfiguration.successfullySaved')}
                            </Typography>

                            <Typography
                                variant="body1"
                                classes={{ root: classes.TypographyCaption }}
                                id="alert-dialog-description"
                            >
                                {t('saveConfiguration.infoText')}
                            </Typography>
                            <Typography
                                id="alert-dialog-description"
                                variant="h5"
                                classes={{ root: classes.saveConfigurationCode }}
                            >
                                <div className={classes.successResult}>
                                    <CheckCircle className={classes.successResultIcon} />
                                    <b>{code}</b>
                                    {IconCopyShareUrl && (
                                        <Tooltip title={t('saveConfiguration.copyConfigurationLink')}>
                                            <AccessibleButton
                                                className={classes.copyShareUrlIcon}
                                                onClick={() => this.onCopyShareUrl(shareUrl)}
                                            >
                                                <IconCopyShareUrl />
                                            </AccessibleButton>
                                        </Tooltip>
                                    )}
                                </div>
                            </Typography>
                            {loadLoginInfoInProgress && (
                                <Typography
                                    variant="body1"
                                    classes={{ root: classes.TypographyCaption }}
                                    id="alert-dialog-description"
                                >
                                    {t('saveConfiguration.loadLoginInfoInProgressText')}
                                </Typography>
                            )}
                        </React.Fragment>
                    )}
                </DialogContent>
                <DialogActions>
                    {!workInProgress && code && (
                        <MainButton
                            onClick={onOkClick}
                            variant="contained"
                            size="medium"
                            className={classes.activeButton}
                        >
                            {t('saveConfiguration.okText')}
                        </MainButton>
                    )}
                </DialogActions>
            </CustomDialog>
        );
    }
}

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