import React, {useCallback} from 'react'
import PropTypes from 'prop-types'
import BEMModule from 'utils/bem'
import styles from './styles.scss'
import {BLOCKS} from '../../config'

const bem = new BEMModule(styles)

const Toolbar = ({children, editor, defaultNode}) => {
    // If there are no toolbar items, don't render them
    if (!React.Children.count(children)) {
        return null
    }

    const isActive = useCallback(
        ({block, mark}) => {
            const value = editor?.value

            if (!value) {
                return false
            }

            if (mark) {
                return value.activeMarks.some(({type}) => type === mark)
            }

            if (block) {
                switch (block) {
                    case BLOCKS.IMAGE:
                    case BLOCKS.VIDEO:
                        return false

                    default:
                        return value.blocks.some(({type}) => type === block)
                }
            }

            return false
        },
        [editor?.value]
    )

    const onItemClick = useCallback(
        (event, type) => {
            const {block, mark} = type

            if (block) {
                event.preventDefault()

                switch (block) {
                    case BLOCKS.IMAGE:
                    case BLOCKS.VIDEO:
                        editor?.insertMedia(block)
                        break

                    default:
                        editor?.setBlocks?.(
                            isActive(type) ? defaultNode : block
                        )
                        break
                }
                return
            }

            if (mark) {
                event.preventDefault()
                editor?.toggleMark?.(mark)
                return
            }
        },
        [editor]
    )

    const classes = bem.classNames('c-editor-toolbar')

    return (
        <div className={classes}>
            {React.Children.map(children, (child) =>
                React.cloneElement(child, {
                    isActive: isActive({
                        block: child.props.block,
                        mark: child.props.mark,
                    }),
                    iconName: child.props.iconName,
                    onClick: onItemClick,
                })
            )}
        </div>
    )
}

Toolbar.propTypes = {
    children: PropTypes.node,
    defaultNode: PropTypes.string,
    editor: PropTypes.object,
}

Toolbar.defaultProps = {
    defaultNode: 'paragraph',
}

export default Toolbar
