﻿import React from 'react';
import Modal from 'react-modal';
import BootstrapTable from 'react-bootstrap-table-next';
import ToolkitProvider, { Search, CSVExport } from 'react-bootstrap-table2-toolkit';
import paginationFactory, { PaginationProvider, PaginationListStandalone, PaginationTotalStandalone, SizePerPageDropdownStandalone } from 'react-bootstrap-table2-paginator';

const customTotal = (from, to, size) => (
    <span className="react-bootstrap-table-pagination-total">
        &nbsp;Mostrando {from} a {to} de {size} resultados
    </span>
);

const { ExportCSVButton } = CSVExport;

class modalBusquedaFiltro extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sizePerPage: 5,
        };
    }

    calculasizePerPageList = (cantidad) => {

        let lista = [];
        // if ((cantidad == 0) || (cantidad == undefined)) {
        //     lista = [{text: '0', value: 0}, {text: 'Todo', value: cantidad }]
        //     return lista;
        // }

        if (cantidad <= 15) {
            lista = [{ text: '5', value: 5 }, { text: '10', value: 10 }, { text: 'Todo', value: cantidad }]
            return lista;
        }

        if (cantidad <= 20) {
            lista = [{ text: '5', value: 5 }, { text: '10', value: 10 }, { text: '15', value: 15 }, { text: 'Todo', value: cantidad }]
            return lista;
        }

        if (cantidad <= 50) {
            lista = [{ text: '5', value: 5 }, { text: '10', value: 10 }, { text: '15', value: 15 }, { text: '25', value: 25 }, { text: '35', value: 35 }, { text: 'Todo', value: cantidad }]
            return lista;
        }
        if (cantidad > 50) {
            lista = [{ text: '5', value: 5 }, { text: '10', value: 10 }, { text: '15', value: 15 }, { text: '25', value: 25 }, { text: '35', value: 35 }, { text: '65', value: 65 }, { text: '85', value: 85 }, { text: '100', value: 100 }, { text: 'Todo', value: cantidad }]
            return lista;
        }
    }


    render() {
        const { selectedModal, contentLabel, label, id, datos, columnas, striped, hover, condensed, selectRow, onDoubleClick, clases, nombreCSV } = this.props;
        const { SearchBar } = Search;
        const name = "btnExportar";
        const clase = "btn btn-sm pull-right flipInX animated";
        const leyenda = "";
        const iclase = "fa fa-download";
        const _sizePerPageList = this.calculasizePerPageList(datos.length);
        const _hideSizePerPage = (datos == undefined) ? true : ((datos.length == 0) ? true : false);

        const NombreCsv = nombreCSV ?? "DatosTabla";
        const csvExport = {
            fileName: `${NombreCsv}.csv`,
            separator: ',',
            ignoreHeader: false,
            noAutoBOM: false,
            blobType: "text/plain;charset=UTF-8",
        };

        const handleExport = () => {
            const filteredColumns = columnas.filter(col => col.csvExport !== false);
            const headers = filteredColumns.map(col => (col.csvText || col.text)).join(';');
            const rows = datos.map(row =>
                filteredColumns.map(col => `"${(row[col.dataField] === '1900-01-01T00:00:00' ? '' : row[col.dataField]) || (row[col.dataField] === 0 ? 0 : '')}"`).join(';')
            );

            const csvContent = `\uFEFF${headers}\n${rows.join('\n')}`;
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);

            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `${NombreCsv}.csv`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        const pageButtonRenderer = ({
            page,
            active,
            disable,
            title,
            onPageChange
        }) => {
            const handleClick = (e) => {
                e.preventDefault();
                onPageChange(page);
            };
            const activeStyle = {};
            if (active) {
                activeStyle.backgroundColor = '#10a599';
                activeStyle.color = 'white';
            } else {
                activeStyle.backgroundColor = 'white';
                activeStyle.color = '#10a599';
            }
            if (typeof page === 'string') {
                activeStyle.backgroundColor = 'white';
                activeStyle.color = '#10a599';
            }
            return (
                <li className="page-item">
                    <a href="javascript:;" onClick={handleClick} style={activeStyle}>{page}</a>
                </li>
            );
        };

        const sizePerPageOptionRenderer = ({
            text,
            page,
            onSizePerPageChange
        }) => (
            <li
                key={text}
                role="presentation"
                className="dropdown-item"
            >
                <a
                    href="javascript:;"
                    tabIndex="-1"
                    role="menuitem"
                    data-page={page}
                    onMouseDown={(e) => {
                        e.preventDefault();
                        onSizePerPageChange(page);
                    }}
                    style={{ color: 'black' }}
                >
                    {text}
                </a>
            </li>
        );

        let optPaginacion = {}
        optPaginacion = {
            //custom: true,
            paginationSize: this.state.sizePerPage,
            pageStartIndex: 0,
            alwaysShowAllBtns: true, // Always show next and previous button
            withFirstAndLast: true, // Hide the going to First and Last page button
            hideSizePerPage: _hideSizePerPage,//false, // Hide the sizePerPage dropdown always
            hidePageListOnlyOnePage: true, // Hide the pagination list when only one page
            firstPageText: '<<',
            prePageText: '<',
            nextPageText: '>',
            lastPageText: '>>',
            nextPageTitle: 'Siguiente Página',
            prePageTitle: 'Página Anterior',
            firstPageTitle: 'Primera Página',
            lastPageTitle: 'Última Página',
            showTotal: true,
            paginationTotalRenderer: customTotal,
            sizePerPageList: _sizePerPageList, // A numeric array is also available. the purpose of above example is custom the text
            variation: 'dropup',
            dataSize: datos.length,
            pageButtonRenderer,
            sizePerPageOptionRenderer
            //page:0,  

        };
        const customStyles = {
            content: {
                position: 'fixed',
                position: 'absolute',
                top: '25%',
                left: '25%',
                right: '25%',
                bottom: '25%',
                //top: '50%',
                //left: '50%',
                //right: 'auto',
                with: '50%',
                height: '67%',
                //bottom: 'auto',
                //marginRight: '-50%',
                //transform: 'translate(-50%, -50%)',
                padding: '5px'
            },
            overlay: {
                backgroundColor: 'rgba(0, 0, 0, 0.75)',
            },
        };
        const rowEvents = {
            onDoubleClick: (e, row, rowIndex) => {
                onDoubleClick(e, row, rowIndex);
            }
        };
        const NoDatos = 'No hay datos que mostrar'

        const renderSizePerPageDropDown = props => {

            return (
                <div className='btn-group'>
                    <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        {props.sizePerPage} <span className="caret"></span>
                    </button>
                    <ul className="dropdown-menu" role="menu">
                        {
                            props.sizePerPageList.map((n, idx) => {
                                return (
                                    <li key={idx}><a className="dropdown-item" onClick={() => {
                                        let pPage = props.page;
                                        // console.log(Math.ceil(datos.length / n.value), props.page)
                                        if (Math.ceil(datos.length / n.value) < props.page) {
                                            pPage = 1;
                                        }

                                        props.onSizePerPageChange(n.value, pPage)
                                    }}>{n.text}</a></li>
                                );
                            })
                        }
                    </ul>
                </div>
            );
        }

        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}>
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h2 className="modal-title" id="exampleModalLabel">{label}</h2>
                        </div>
                        <div className="modal-body">
                            <div className="row">
                                <ToolkitProvider
                                    keyField={id}
                                    data={datos}
                                    columns={columnas}
                                    search
                                // exportCSV={csvExport}
                                >
                                    {
                                        props => (
                                            <div>
                                                {/*<h3>Input something at below input field:</h3>*/}
                                                {/*<ExportCSVButton { ...props.csvProps }>Exportar CSV</ExportCSVButton>*/}

                                                <div className='row'>
                                                    <div className={"col-xs-12 col-sm-12 col-md-12 col-lg-12"} style={{ margin: "15px 0" }}>

                                                        <div style={{ float: "left" }}>
                                                            {/* <ExportCSVButton {...props.csvProps} className={clase}  >
                                                                <i className={iclase} ></i>
                                                            </ExportCSVButton> */}
                                                            <button onClick={handleExport} className={clase}>
                                                                <i className={iclase} ></i>
                                                            </button>
                                                        </div>
                                                        <div style={{ float: "right" }}>
                                                            <SearchBar {...props.searchProps} placeholder="Buscar" />
                                                        </div>

                                                    </div>
                                                </div>
                                                <PaginationProvider
                                                    pagination={paginationFactory(optPaginacion)}
                                                >
                                                    {
                                                        ({
                                                            paginationProps,
                                                            paginationTableProps
                                                        }) => (
                                                            <div>

                                                                <div className='table-responsive'>
                                                                    <BootstrapTable
                                                                        {...props.baseProps}
                                                                        {...paginationTableProps}
                                                                        striped={striped}
                                                                        hover={hover}
                                                                        condensed={condensed}
                                                                        selectRow={selectRow}
                                                                        //pagination={paginationFactory(optPaginacion)}
                                                                        rowEvents={rowEvents}
                                                                        className={clases}
                                                                        noDataIndication={NoDatos}
                                                                    />
                                                                </div>

                                                                {/* {renderSizePerPageDropDown({ ...paginationProps })}

                                <PaginationTotalStandalone
                                  {...paginationProps}
                                />

                                <PaginationListStandalone
                                  {...paginationProps}
                                />*/}
                                                            </div>
                                                        )
                                                    }
                                                </PaginationProvider>

                                            </div>

                                        )
                                    }
                                </ToolkitProvider>
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-secondary" data-dismiss="modal" onClick={this.props.cerrarModal}>Cerrar</button>
                            <button type="button" className="btn btn-primary" onClick={this.props.seleccionModal}>Seleccionar</button>
                        </div>
                    </div>
                </div>
            </Modal>
        )



    }
}
export default modalBusquedaFiltro;
