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

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

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

    componentDidUpdate(prevProps) {
        // todo: add open toggle persitent 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, root_name, deleteItem} = this.props;
        
        return (
            <div className={'doctree--block-item ' + (isDragging ? 'sortable-chosen' : '')}
                 ref={provided.innerRef}
                 {...provided.draggableProps}
                 {...provided.dragHandleProps}
            >
                <div className='doctree--block-item--inner' style={(isDragging ? {
                    background: isOverTarget ? theme.bgPage : ('dark' === theme.name ? '#271f25' : '#ae979a'),
                    border: '1px solid ' + theme.textColorLight,
                } : {
                    background: 'rgba(0, 0, 0, 0.15)',
                    border: '1px solid transparent'
                })}
                >
                    <BlockFactory uid={uid}
                                  head={BlockItemHead}
                                  deleteItem={deleteItem}
                                  open={this.state.open}
                                  onToggle={this.toggle}
                                  data={data}
                                  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;