import React from 'react';
import PropTypes from 'prop-types';
import {SketchPicker} from 'react-color';
import reactCSS from 'reactcss'
import tinycolor from 'tinycolor2'

export default class ColorPickerEditor extends React.Component {
    static propTypes = {
        value: PropTypes.string,
        commit: PropTypes.func.isRequired,
    };

    state = {
        displayColorPicker: false,
    };

    handleChange = newColor => {
        this.props.commit(newColor.hex);
    };

    handleClick = () => {
        this.setState({ displayColorPicker: !this.state.displayColorPicker })
    };

    handleClose = () => {
        this.setState({ displayColorPicker: false })
    };

    render() {
        const lightBackground = tinycolor(this.props.value).toHsl().l < .4;
        const styles = reactCSS({
            'default': {
                color: {
                    width: '36px',
                    height: '14px',
                    borderRadius: '2px',
                    background: this.props.value,
                    display: 'inline-block',
                    verticalAlign: 'middle',
                },
                hex: {
                    color: this.props.value,
                    paddingLeft: '15px',
                },
                swatch: {
                    padding: '5px',
                    background: lightBackground ? '#f0f0f0' : '#222',
                    borderColor: lightBackground ? '#222' : '#f0f0f0',
                    borderStyle: 'solid',
                    borderWidth: '1px',
                    borderRadius: '4px',
                    boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
                    display: 'inline-block',
                    cursor: 'pointer',
                },
                popover: {
                    position: 'absolute',
                    zIndex: '2',
                },
                cover: {
                    position: 'fixed',
                    top: '0px',
                    right: '0px',
                    bottom: '0px',
                    left: '0px',
                },
            },
        });

        if (!this.props.value) {
            this.props.commit('#ffffff');
        }

        return (
            <div>
                <div style={ styles.swatch } onClick={ this.handleClick }>
                    <div style={ styles.color } />
                    <code style={ styles.hex }>{ this.props.value }</code>
                </div>
                { this.state.displayColorPicker ? <div style={ styles.popover }>
                    <div style={ styles.cover } onClick={ this.handleClose }/>
                    <SketchPicker
                        color={ this.props.value }
                        onChange={ this.handleChange }
                        disableAlpha={ true }
                    />
                </div> : null }

            </div>
        )
    }
}
