import React from 'react';
import Modal from 'react-modal';
//import {SortableTreeWithoutDndContext as SortableTree,  toggleExpandedForAll } from 'react-sortable-tree';
//import SortableTree, {  toggleExpandedForAll } from '@nosferatu500/react-sortable-tree';
import SortableTree, { toggleExpandedForAll } from 'react-sortable-tree-patch-react-17';
import FormBotones from '../botonera/formBotones.jsx';
import CajaTexto from '../cajaTexto/cajaTexto.jsx';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMinus, faPlus, faBackward, faForward } from '@fortawesome/free-solid-svg-icons';
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: [],
            botonesFrm: [
                {
                    name: "expandir",
                    clase: "btn btn-sm pull-right flipInX animated",
                    evento: this.toggleNodeExpansion.bind(this, true),
                    leyenda: "",
                    iclase: faPlus,
                    tooltip: "Expandir"
                },
                {
                    name: "expandirNo",
                    clase: "btn btn-sm pull-right flipInX animated",
                    evento: this.toggleNodeExpansion.bind(this, false),
                    leyenda: "",
                    iclase: faMinus,//"fa fa-pencil",
                    tooltip: "Contraer"
                },
                {
                    name: "selectPrevMatch",
                    clase: "btn btn-sm pull-right flipInX animated",
                    evento: this.selectPrevMatch,
                    leyenda: "",
                    iclase: faBackward,
                    tooltip: "Anterior"
                },
                {
                    name: "selectNextMatch",
                    clase: "btn btn-sm pull-right flipInX animated",
                    evento: this.selectNextMatch,
                    leyenda: "",
                    iclase: faForward,
                    tooltip: "Siguiente"
                },
            ],
            FrmAttributes: { readOnly: false, focus: false, label: '', float: 'left', hidden: 'unset' },
            BusquedaTxT: { value: "", attributes: { readOnly: false, focus: false, label: ((!props.label) ? 'Cuenta Contable' : props.label), hidden: 'unset', Editando: false, maxLength: "200", placeholder: 'Buscar...' } },
        }
    }

    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 => {
        let _BusquedaTxT = this.state.BusquedaTxT;
        _BusquedaTxT.value = e.target.value;
        this.setState({
            searchString: e.target.value, BusquedaTxT: _BusquedaTxT
        });
    };

    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
        });
    };
    render() {
        const { selectedModal, contentLabel, label, id } = this.props;
        const { searchString, searchFocusIndex, searchFoundCount, treeData } = this.state;
        const customStyles2 = {
            content: {
                top: '50%',
                left: '50%',
                right: 'auto',
                marginRight: '-50%',
                transform: 'translate(-50%, -50%)',
                padding: '5px'
            }
        };
        const customStyles = {
            content: {
                position: 'absolute',
                top: '25%',
                left: '25%',
                right: '25%',
                bottom: '25%',
                with: '60%',
                height: '60%',

                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 className="row">
                                    <div className="col-md-12">
                                        <CajaTexto col="10" id="BusquedaTxT" type="text" label={this.state.BusquedaTxT.attributes.label} value={this.state.BusquedaTxT.value} attributes={this.state.BusquedaTxT.attributes} onChangeInput={this.handleSearchOnChange} />
                                    </div>
    </div>*/}
                                <div className="row">
                                    <div className="row">
                                        <div className="col-md-12">
                                            <CajaTexto col="12" id="BusquedaTxT" type="text" label={this.state.BusquedaTxT.attributes.label} value={this.state.BusquedaTxT.value} attributes={this.state.BusquedaTxT.attributes} onChangeInput={this.handleSearchOnChange} />

                                        </div>
                                        <div className="col-md-12">
                                            <div className="form-group">
                                                <FormBotones col='4' attributes={this.state.FrmAttributes} botones={this.state.botonesFrm} />
                                                <div className="col-md-2" style={{ textAlign: "left", padding: "25px" }}>
                                                    <div className="form-group"><label>{searchFocusIndex} / {searchFoundCount}</label></div>
                                                </div>
                                            </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);

                                                this.handleNodeClick(node);
                                            },
                                            style:
                                                node === this.state.nodeClicked
                                                    ? {
                                                        color: "#d73220",
                                                        border: "3px solid #d73220",
                                                    }
                                                    : {}
                                        }
                                    }}
                                    style={{ width: '100%', height: '80%', overflow: 'hidden', fontSize: '11px' }}
                                />


                            </div>


                        </div>

                        <div className="modal-footer">
                            <button type="button" className="btn btnSecondaryStyle" 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;

