import React from 'react';
import Modal from 'react-modal';
import SortableTree, { toggleExpandedForAll } from 'react-sortable-tree';
import LoaderHOC from  '../../../components/UI/HOC/LoaderHOC.js';



const maxDepth = 5;

const alertNodeInfo = ({ node, path, treeIndex }) => {
    const objectString = Object.keys(node)
        .map(k => (k === 'children' ? 'children: Array' : `${k}: '${node[k]}'`))
        .join(',\n   ');

    global.alert(
        'Info passed to the button generator:\n\n' +
        `node: {\n   ${objectString}\n},\n` +
        `path: [${path.join(', ')}],\n` +
        `treeIndex: ${treeIndex}`
    );
};

class modalBusquedaTree extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            searchString: '',
            searchFocusIndex: 0,
            searchFoundCount: null,
            treeData: [],
        }
    }

    // componentDidMount = () => {

    //     }

    componentDidUpdate = (prevProps, prevState, snapshot) => {

        if (this.props.listatree !== prevProps.listatree) {
            const _treeData = this.props.listatree;
            this.setState({ treeData: _treeData });
          
        }
    }


    handleTreeOnChange = (treeData) => {
        
        this.setState({ treeData });
    };

    handleSearchOnChange = e => {
        this.setState({
            searchString: e.target.value,
        });
    };

    customSearchMethod = ({ node, searchQuery }) =>
        searchQuery && (
            node.title.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1 ||
            node.subtitle.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1);

    selectPrevMatch = () => {
        const { searchFocusIndex, searchFoundCount } = this.state;

        this.setState({
            searchFocusIndex:
                searchFocusIndex !== null
                    ? (searchFoundCount + searchFocusIndex - 1) % searchFoundCount
                    : searchFoundCount - 1,
        });
    };

    selectNextMatch = () => {
        const { searchFocusIndex, searchFoundCount } = this.state;

        this.setState({
            searchFocusIndex:
                searchFocusIndex !== null
                    ? (searchFocusIndex + 1) % searchFoundCount
                    : 0,
        });
    };

    toggleNodeExpansion = expanded => {
        this.setState(prevState => ({
            treeData: toggleExpandedForAll({
                treeData: prevState.treeData,
                expanded,
            }),
        }));
    };
    handleNodeClick = (node) => {
        this.setState({
          nodeClicked: node
        });
        console.log(`node: ${JSON.stringify(node)}`);
      };
    render() {
        const { selectedModal, contentLabel, label, id } = this.props;
        const { searchString, searchFocusIndex, searchFoundCount, treeData } = this.state;
        const customStyles2 = {
            content: {
                top: '50%',
                left: '50%',
                right: 'auto',
                //bottom: 'auto',
                marginRight: '-50%',
                transform: 'translate(-50%, -50%)',
                padding: '5px'
            }
        };
        const customStyles = {
            content: {
                //position: 'fixed',
                position:'absolute',
                top: '25%',
                left: '25%',
                right: '25%',
                bottom: '25%',                  
                //top: '50%',
                //left: '50%',
                //right: 'auto',
                with: '50%',
                height: '60%',
                //bottom: 'auto',
                //marginRight: '-50%',
                //transform: 'translate(-50%, -50%)',
                padding: '5px'

            },              
            overlay: {
                backgroundColor: 'rgba(0, 0, 0, 0.75)',
              },
        };
        return (

            <Modal
                isOpen={selectedModal}
                contentLabel={contentLabel}
                style={customStyles}
                ariaHideApp={false}
            >
                <div className="">
                    <div className="">

                        <div className="modal-header">                            
                            <button type="button" className="close" data-dismiss="modal" aria-label="Close" onClick={()=>{this.props.cerrarModal(id)}}>
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h2 className="modal-title" id="exampleModalLabel">{label}</h2>
                        </div>

                        <div className="modal-body">

                            <div >
                                <div className="row">
                                    <div className="col-md-12">
                                        <div className="col-xs-11 col-sm-11 col-md-11 col-lg-11">
                                            <input type="text" className="form-control" name="Buscar" placeholder="Buscar..." onChange={this.handleSearchOnChange}></input>
                                        </div>

                                    </div>
                                </div>


                                <div className="row">
                                    <br></br>
                                    <div className="col-md-12" >
                                        <div className="col-md-4">

                                            <a key={"expandir"} id={"expandir"}  type="button" className={"btn btn-sm pull-left"} onClick={this.toggleNodeExpansion.bind(this, true)}><i className={"fa fa-plus"}></i>{""}</a>
                                            <a key={"expandirNo"} id={"expandirNo"} type="button" className={"btn btn-sm pull-left"} onClick={this.toggleNodeExpansion.bind(this, false)}><i className={"fa fa-minus"}></i>{""}</a>
                                            <a key={"selectPrevMatch"} id={"selectPrevMatch"}  type="button" className={"btn btn-sm pull-left"} onClick={this.selectPrevMatch}><i className={"fa fa-backward"}></i>{""}</a>
                                            <a key={"selectNextMatch"} id={"selectNextMatch"}  type="button" className={"btn btn-sm pull-left"} onClick={this.selectNextMatch}><i className={"fa fa-forward"}></i>{""}</a>
                                        </div>
                                        <div className="col-md-8" style={{ textAlign: "left" }}>
                                            <div className="form-group"><label>{searchFocusIndex} / {searchFoundCount}</label></div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div style={{ height: 300 }}>



                                <SortableTree
                                    treeData={treeData}
                                    onChange={this.handleTreeOnChange}
                                    onMoveNode={({ node, treeIndex, path }) =>
                                        global.console.log(
                                            'node:',
                                            node,
                                            'treeIndex:',
                                            treeIndex,
                                            'path:',
                                            path
                                        )
                                    }
                                    maxDepth={maxDepth}
                                    searchMethod={this.customSearchMethod}
                                    searchQuery={searchString}
                                    searchFocusOffset={searchFocusIndex}
                                    canDrag={false}
                                    onlyExpandSearchedNodes={true}
                                    rowHeight={50}
                                    slideRegionSize={20} //100
                                    scaffoldBlockPxWidth={32} //44
                                    searchFinishCallback={matches =>
                                        this.setState({
                                            searchFoundCount: matches.length,
                                            searchFocusIndex:
                                                matches.length > 0 ? searchFocusIndex % matches.length : 0,
                                        })
                                    }
                                    isVirtualized={true}
                                    generateNodeProps={rowInfo => {
                                        const { node } = rowInfo;
                                        return{

                                        onClick: () => {
                                            this.props.onSelectedRow(rowInfo,id);
                                           // alertNodeInfo(rowInfo)
                                           this.handleNodeClick(node);
                                          },
                                          style:
                                            node === this.state.nodeClicked
                                              ? {
                                                  color: "#10a599",
                                                  border: "3px solid #10a599",
                                                }
                                              : {}                                
                                    }
                                    }}
                                    style={{ width: '100%', height: '80%', overflow: 'hidden', fontSize: '11px' }}
                                />


                            </div>


                        </div>

                        <div className="modal-footer">
                            <button type="button" className="btn btn-secondary" data-dismiss="modal" onClick={()=>{this.props.cerrarModal(id)}}>Cerrar</button>
                            <button type="button" className="btn btn-primary" onClick={()=>{this.props.seleccionModal(id)}}>Seleccionar</button>
                        </div>
                    </div>  
                </div>
            </Modal>
        )



    }
}
export default modalBusquedaTree;
//export default LoaderHOC('treeData')(modalBusquedaTree); 
