import React from 'react';
import PropTypes from 'prop-types';
import { t, translateComponent } from 'Framework/i18n';
import Input from 'Framework/Components/Input';
import CustomDialog from 'Shared/Components/CustomDialog';
import MainButton from 'Shared/Components/MainButton';
import './Styles.scss';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';

export class CustomTitleEditor extends React.Component {
    static propTypes = {
        DialogComponent: PropTypes.elementType,
        show: PropTypes.bool,
        title: PropTypes.string,
        onClose: PropTypes.func,
        setConfigurationName: PropTypes.func,
        onChange: PropTypes.func,
    };

    state = {
        message: null,
    };

    onChange = () => {
        if (this.input.value.length === 0) {
            this.setState({
                message: this.t('customTitleEditor.emptyTitle'),
            });
            this.input.element.focus();
        } else {
            this.props.onChange(this.input.value);
            this.props.onClose();
            if (this.state.message) {
                this.setState({
                    message: null,
                });
            }
        }
    };

    render() {
        const { show, onClose, title } = this.props;

        return (
            <CustomDialog
                open={show}
                dialogTitle={t('customTitleEditor.infoText')}
                onClose={onClose}
                onCancel={onClose}
                className={'customTitleEditor-dialog'}
            >
                <DialogContent>
                    <Input
                        className="customTitleEditor-input"
                        value={title}
                        ref={ref => (this.input = ref)}
                        autoFocus={true}
                        onEnterPressed={this.onChange}
                    />

                    {this.state.message && (
                        <div className="customTitleEditor-message">{this.state.message}</div>
                    )}
                </DialogContent>
                <DialogActions>
                    <MainButton
                        className="primary-button customTitleEditor-ok"
                        onClick={this.onChange}
                        variant="contained"
                    >
                        {t('customTitleEditor.okText')}
                    </MainButton>
                </DialogActions>
            </CustomDialog>
        );
    }
}

export default translateComponent(CustomTitleEditor);
