import Griddle, { utils } from "griddle-react";
import PropTypes from 'prop-types';
import React, { Component, Fragment } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { Button } from '@material-ui/core';
import TextField from '@material-ui/core/TextField';
import GriddleCustomTable from "../organisms/GriddleCustomTableComponent";
import GriddleCustomNextButton from "../organisms/GriddleCustomNextButton"
import GriddleCustomPreviousButton from "../organisms/GriddleCustomPreviousButton"
import Loader from './loader'
import IconSearch from '@material-ui/icons/Search';
import NoResult from './../atoms/NoResult';
import _ from "lodash";

//insights
//
//https://codesandbox.io/s/pw9zy43v1m?module=%2FGrid.js
const styles = theme => ({
    textField: {
        textAlign: 'center',
        justifyContent: 'center',
        margin: 0,
        '& input': {
            fontWeight: '300',
            color: theme.palette.primary.dark,
            backgroundColor: theme.palette.background.grey,
            minWidth: '75vw',
            padding: 0,
            margin: 0,
            paddingLeft: theme.spacing(2),
            [theme.breakpoints.up('md')]: {
                minWidth: '85vw',
              },
        }
    },
    griddle: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        '& .griddle-pagination': {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
        },
    },
    button: {
        padding: theme.spacing(2, 0),
        boxShadown: '0px',
        backgroundColor: theme.palette.background.grey,
    },
    filterForm: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: theme.palette.background.grey,
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100% !important',
        [theme.breakpoints.up('md')]: {
            justifyContent: 'space-evenly',
          },
    },
})

const CustomTableBody = ({ rowIds, Row, style, className }) => (
    <div style={style} className={className}>
        {rowIds && rowIds.valueSeq().map(r => <Row key={r} griddleKey={r} />)}
    </div>
);

class Grid extends Component {

    state = {
        loading: true,
        success: false,
        data: {},
        currentPage: 1,
        pageSize: 12,
        recordCount: 0,
        promoted: false,
        filterText: "",
    };

    async componentDidMount() {
        
        this.setState({pageSize:this.props.limit})
        let data = sessionStorage.getItem(this.props.type+'_currentPage');
        let current;
        if(data){
            current=data;
        }else{
            current=this.state.currentPage;
        }
        this.props.dataFetcher(
            {
                offset: ((current-1)*this.props.limit)+1,
                limit: this.props.limit
            }
        );
    }

    UNSAFE_componentWillReceiveProps(nextProps) {
        
        this.setState({ data: nextProps.data });
        this.setState({ currentPage: nextProps.currentPage });
        this.setState({ recordCount: nextProps.recordCount });
        this.setState({ loading: nextProps.loading });
        this.setState({ limit: nextProps.limit });


        const { currentPage, pageSize, filterText, promoted } = this.state;

        if (nextProps.promoted != this.state.promoted) {
            let data = sessionStorage.getItem(this.props.type+'_currentPage');
            let current;
            if(data){
                current=data;
            }else{
                current=this.state.currentPage;
            }
            this.setState({ promoted: nextProps.promoted });
            this.props.dataFetcher(
                {
                    offset: ((current-1)*(this.state.pageSize+1))+1,
                    limit: this.state.pageSize,
                    keyword: filterText,
                    isPromoted: nextProps.promoted
                }
            );
        }

        window.scrollTo(0, 0);
    }

    _onNext = () => {
        const { currentPage, pageSize, filterText, promoted } = this.state;
        this.props.dataFetcher({ offset: currentPage * pageSize, limit: pageSize, keyword: filterText, isPromoted: promoted })
        sessionStorage.setItem(this.props.type+'_currentPage', currentPage+1);

    };

    _onPrevious = () => {
        const { currentPage, pageSize, filterText, promoted } = this.state;
        this.props.dataFetcher({ offset: (currentPage - 2) * pageSize + 1, limit: pageSize, keyword: filterText, isPromoted: promoted });
        sessionStorage.setItem(this.props.type+'_currentPage', currentPage-1);

    };

    _onGetPage = pageNumber => {
        const { pageSize, filterText, promoted } = this.state;
        this.props.dataFetcher({ offset: (pageNumber - 1) * pageSize + 1, limit: pageSize, keyword: filterText, isPromoted: promoted });
        
    };

    _onFilter = filterText => {
        sessionStorage.setItem(this.props.type+'_currentPage', 1);
        this.setState({ currentPage: 1 });
        const { currentPage, pageSize, promoted } = this.state;
        this.setState({ filterText });
        this.props.dataFetcher({ offset: (currentPage - 1) * pageSize + 1, limit: pageSize, keyword: filterText, isPromoted: promoted });
    };

    searchChange = e => {
        this.setState({ filterText: e.target.value });
    }

    searchSubmit = () => {
        const { currentPage, pageSize, promoted, filterText } = this.state;
        sessionStorage.setItem(this.props.type+'_currentPage', 1);
        this.props.dataFetcher({ offset: 1, limit: pageSize, keyword: filterText, isPromoted: promoted });
    }

    render() {
        const { classes, placeholder } = this.props
        const style = {
            styles: {
                TableBody: {
                    display: 'flex',
                    flexWrap: 'wrap',
                    justifyContent: 'space-around'
                },
                Pagination: {
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    paddingTop: '32px',
                },
                NextButton: {
                    fontSize: '0.9em',
                    fontWeight: '600',
                    fontFamily: 'Dosis',
                    textTransform: 'inherit',
                    marginLeft: '64px',
                    marginRight: '64px',
                    marginTop: '32px',
                    marginBottom: '16px',
                    padding: '9px 16px',
                    borderRadius: '3px',
                    backgroundColor: 'transparent',
                    border: '1px solid #E8E8E9',
                    color: '#787B7D',
                    cursor: 'pointer',
                },
                PreviousButton: {
                    fontSize: '0.9em',
                    fontWeight: '600',
                    fontFamily: 'Dosis',
                    textTransform: 'inherit',
                    marginLeft: '64px',
                    marginRight: '64px',
                    marginTop: '32px',
                    marginBottom: '16px',
                    padding: '9px 16px',
                    borderRadius: '3px',
                    backgroundColor: 'transparent',
                    border: '1px solid #E8E8E9',
                    color: '#787B7D',
                    cursor: 'pointer',
                },
                PageDropdown: {
                    fontSize: '0.9em',
                    fontWeight: '600',
                    fontFamily: 'Dosis',
                    display: 'none',
                },
            }
        }

        const { filterText, data, currentPage, pageSize, recordCount, loading } = this.state;

        const NewLayout = ({ Table, Pagination, Filter }) => (
            <div>
                {/* <Filter /> */}
                <Table />
                <Pagination />
            </div>
        );

        const rowDataSelector = (state, { griddleKey }) => {
            // console.debug("rowDataSelector")
            // console.debug(state)
            return state
                .get("data")
                .find(rowMap => rowMap.get("griddleKey") === griddleKey)
                .toJSON()
        }

        const enhancedWithRowData = utils.connect((state, props) => ({
            // rowData will be available into MyCustomComponent
            rowData: rowDataSelector(state, props),

        }));


        return (
            <div>
                {this.props.searchable &&
                    <div className={classes.filterForm}>
                        <TextField
                            id="standard-search"
                            disabled={loading}
                            name="search"
                            value={filterText}
                            onChange={this.searchChange}
                            placeholder={placeholder}
                            className={classes.textField}
                            InputLabelProps={{
                                shrink: true,
                            }}
                            margin="dense"
                            variant="filled"
                            onKeyPress={(ev) => {
                                if (ev.key === 'Enter') {
                                    this.searchSubmit()
                                }
                            }}
                            type="search"
                        />
                        <Button onClick={this.searchSubmit}
                            disabled={loading}
                            variant="contained"
                            className={classes.button}>
                            <IconSearch />
                        </Button >
                    </div>
                }
                {loading ?
                    (<Loader />)
                    : !_.isEmpty(data) ? (
                        <Griddle
                            className={classes.griddle}
                            data={data}
                            pageProperties={{
                                currentPage,
                                pageSize,
                                recordCount,
                            }}
                            useCustomPagerComponent="true"
                            components={{
                                Layout: NewLayout,
                                Row: this.props.CustomRowComponent,
                                TableContainer: GriddleCustomTable,
                                TableBody: CustomTableBody,
                                PreviousButton: GriddleCustomPreviousButton,
                                NextButton: GriddleCustomNextButton,
                            }}
                            events={{
                                onNext: this._onNext,
                                onPrevious: this._onPrevious,
                                onGetPage: this._onGetPage,
                                onFilter: this._onFilter
                            }}
                            styleConfig={style}
                        />
                    ) : (<NoResult text='Aucun résultat.' />)
                }
            </div>
        )
    }

}

Grid.defaultProps = {
    offset: 1,
    limit: 12,
    searchable: true
}

Grid.propTypes = {
    dataFetcher: PropTypes.func.isRequired,
    CustomRowComponent: PropTypes.any.isRequired,
    data: PropTypes.any,
    searchable: PropTypes.bool
}

export default withStyles(styles)(Grid);
