import { RichTextToolbarButton } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { registerFormatType } from '@wordpress/rich-text';
import { applyFormat } from '@wordpress/rich-text';
import { RichTextShortcut } from '@wordpress/block-editor';
import {
    BlockControls
} from '@wordpress/block-editor';
import { Toolbar, Popover, GradientPicker } from '@wordpress/components';
import { compose } from "@wordpress/compose";
import { useState } from "@wordpress/element";
import { withSelect } from "@wordpress/data";
import { styles } from "@wordpress/icons";

const name = 'blockify/gradient';

const defaultGradients = [
    {
        gradient: "linear-gradient(0deg,var(--wp--preset--color--black) 0%,var(--wp--preset--color--white) 100%)",
        slug: 'black-white',
        name: 'Black White'
    }
];

const Edit = ( { isActive, value, onChange, gradients } ) => {
    const [ gradient, setGradient ] = useState( '' );
    const [ isOpen, setIsOpen ]     = useState( false );

    return (
        <BlockControls>
            <RichTextShortcut
                type={ 'primary' }
                character={ 'g' }
            />
            <RichTextToolbarButton
                icon={ styles }
                title={ __( 'Gradient', 'blockify' ) }
                isActive={ isActive }
                shortcutType={ 'primary' }
                shortcutCharacter={ 'g' }
                onClick={ () => setIsOpen( ! isOpen ) }
            />
            { isOpen &&
			  <Toolbar className={ 'blockify-components-toolbar' }>
				  <Popover
					  position={ 'bottom center' }
					  className={ 'blockify-gradient-text-control' }
					  focusOnMount={ 'container' }
					  onFocusOutside={ () => setIsOpen( false ) }
				  >
					  <GradientPicker
						  value={ gradient }
						  gradients={ gradients }
						  onChange={ newGradient => {
                              setGradient( newGradient );

                              onChange( applyFormat( value, {
                                  type: name,
                                  attributes: {
                                      style: 'background:' + newGradient,
                                      class: 'has-gradient-text'
                                  }
                              } ) )
                          } }
					  />
				  </Popover>
			  </Toolbar>
            }
        </BlockControls>

    );
};

registerFormatType( name, {
    title: __( 'Gradient', 'blockify' ),
    tagName: 'span',
    className: 'has-gradient-text',
    attributes: {
        style: 'style',
        class: 'class',
    },
    edit: compose( withSelect( select => {
        const { gradients } = select( 'core/block-editor' ).getSettings();

        return {
            gradients: gradients ? gradients : defaultGradients
        };
    } ) )( Edit )
} );


