import React from "react";
import {MdDragHandle} from 'react-icons/md';
import {withTheme} from "../../lib/theme";
import BlockFactory from './BlockFactory';
import BlockItemHead from './BlockItemHead';

class BlockItem extends React.Component {
    state = {
        open: false,
    };

    toggle = () => {
        this.setState({open: !this.state.open});
    };

    componentDidUpdate(prevProps) {
        // todo: add open toggle persistent to elem data payload (like addSave, rmSave [will be] done), to have it open again after drag-drop when it was open
        if(prevProps.data !== this.props.data) {
            this.setState({open: false});
        }
    }

    render() {
        const {isDragging, provided, theme, isOverTarget, uid, data, index, t, root_name, deleteItem} = this.props;

        return (
            <div className={'doctree--block-item ' + (isDragging ? 'sortable-chosen' : '')}
                 ref={provided.innerRef}
                 {...provided.draggableProps}
            >
                <div className='doctree--block-item--inner' style={(isDragging ? {
                    background: isOverTarget ? theme.bgPage : ('dark' === theme.name ? '#271f25' : '#ae979a'),
                    border: '1px solid ' + theme.textColorLight,
                } : {
                    background: theme.drop.item,
                    border: '1px solid transparent'
                })}
                >
                    {/* dnd throws error "can not finde draghandle" etc., doesn't recognize it during initial render when only in blockfacotry, next part is just a tricky-fix */}
                    {/*<div {...provided.dragHandleProps} style={{display: 'none'}}/>*/}

                    {/* tmp draghandle fix: todo, allow head dragging */}
                    <div style={{position: 'absolute', top: '6px', left: 0, padding: 6}} {...provided.dragHandleProps}><MdDragHandle size={'1.125em'} color={('dark' === theme.name ? theme.textColorLight : theme.textColor)}/></div>

                    <BlockFactory uid={uid}
                                  head={(p) => <BlockItemHead provided={provided} {...p}/>}
                                  deleteItem={deleteItem}
                                  open={this.state.open}
                                  onToggle={this.toggle}
                                  data={data}
                                  t={t}
                                  root_name={root_name}
                                  index={index}/>
                </div>
            </div>
        );
    }
}

const BlockFactoryDragItemStyled = withTheme(BlockItem);

const BlockFactoryDragItem = React.forwardRef((props, ref) => {
    return <BlockFactoryDragItemStyled {...props} innerRef={ref}/>
});

export default BlockFactoryDragItem;