import React, {useCallback, useRef, useState} from 'react'
import PropTypes from 'prop-types'
import hoistNonReactStatics from 'hoist-non-react-statics'
import {Editor as BaseEditor} from 'slate-react'
import {Value} from 'slate'
import Toolbar from './partials/toolbar'
import {BLOCKS, DEFAULT_PLUGINS, MARKS, SCHEMA} from './config'
import styles from './styles.scss'
import BEMModule from 'utils/bem'

const bem = new BEMModule(styles)

const INITIAL_VALUE = {
    document: {
        nodes: [
            {
                object: 'block',
                type: 'paragraph',
                nodes: [],
            },
        ],
    },
}

const Editor = ({
    className,
    defaultNode,
    initialValue,
    placeholder,
    plugins,
    readOnly,
    spellCheck,
    toolbar,
    value: controlledValue,
    onChange,
}) => {
    const editor = useRef()
    const isControlled = typeof controlledValue !== undefined
    const [stateValue, setValue] = useState(
        Value.isValue(initialValue)
            ? initialValue
            : Value.fromJSON(initialValue)
    )

    // declare the value to be the controlled value if the component is controlled,
    // otherwise, get the value from the state.
    window.VALUE = Value
    const value = isControlled
        ? (Value.isValue(controlledValue) && controlledValue) ||
          Value.fromJSON(controlledValue || initialValue)
        : stateValue

    /**
     * On change, change the value of the editor
     */
    const change = useCallback(
        ({value}) => {
            if (!isControlled) {
                setValue(value)
            }

            onChange?.(value)
        },
        [isControlled]
    )

    const classes = bem.classNames('c-editor', className)
    const editorClasses = bem.classNames('c-editor__editor')

    return (
        <div className={classes}>
            <Toolbar defaultNode={defaultNode} editor={editor.current}>
                {toolbar}
            </Toolbar>

            <BaseEditor
                className={editorClasses}
                plugins={plugins}
                readOnly={readOnly}
                ref={editor}
                placeholder={placeholder}
                schema={SCHEMA}
                spellCheck={spellCheck}
                value={value}
                onChange={change}
            />
        </div>
    )
}

Editor.propTypes = {
    autoFocus: PropTypes.bool,
    className: PropTypes.string,
    defaultNode: PropTypes.string,
    initialValue: PropTypes.object,
    placeholder: PropTypes.string,
    plugins: PropTypes.array,
    readOnly: PropTypes.bool,
    spellCheck: PropTypes.bool,
    toolbar: PropTypes.array,
    value: PropTypes.object,
    onChange: PropTypes.func,
}

Editor.defaultProps = {
    defaultNode: 'paragraph',
    initialValue: INITIAL_VALUE,
    plugins: DEFAULT_PLUGINS,
    spellCheck: true,
}

Editor.blocks = BLOCKS
Editor.marks = MARKS

export default hoistNonReactStatics(React.memo(Editor), Editor)
