import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { TextField, Snackbar, withStyles } from '@material-ui/core';
import MinimizeIcon from '@material-ui/icons/Minimize';
import AddIcon from '@material-ui/icons/Add';
import RemoveIcon from '@material-ui/icons/Remove';
import Nestable from 'react-nestable';
import api from '../../../api';
import { titleCase } from '../../../library/Utils';
import Autocomplete from '@material-ui/lab/Autocomplete';
import MuiAlert from '@material-ui/lab/Alert';
import Constant from '../../../library/Constant';

const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',
        maxWidth: 500,
        backgroundColor: theme.palette.background.paper,
    },
    nested: {
        paddingLeft: theme.spacing(4),
    },
}));

const Alert = withStyles({
})((props) => <MuiAlert elevation={6} variant="filled" {...props} />);

const type = [
    {
        value: '1',
        label: 'KPI',
    },
    {
        value: '2',
        label: 'KPI',
    },
];

const companies = [
    {
        value: '',
        label: '',
    },
    {
        value: '1',
        label: 'TIA',
    },
    {
        value: '2',
        label: 'TIA',
    },
];

export default class VisualReportItems extends Component {
    constructor(props) {
        super(props)
        this.state = {
            open: false,
            items: [],
            arrayCollapse: [],
            defaultCollapsed: false,
            listReport: null,
            report: null,
            listCompany: null,
            company: null,
            alert: false,
            tipeAlert: '',
            messageAlert: '',
            realItems: []
        }
    }

    componentDidMount() {
        console.log(this.props.height)
        this.getReportType()
    }

    getReportType() {
        api.create().getReportType().then((response) => {
            this.getCompanyActive()
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        let data = response.data.data
                        let reportData = data.map((item) => {
                            return {
                                report_id: item.report_id,
                                report_name: item.report_name,
                            }
                        })
                        let defaultProps = {
                            options: reportData,
                            getOptionLabel: (option) => titleCase(option.report_name),
                        };

                        this.setState({ listReport: defaultProps, report: reportData[0] })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getCompanyActive() {
        api.create().getPerusahaanActive().then((response) => {
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        let data = response.data.data
                        let companyData = data.map((item) => {
                            return {
                                company_id: item.company_id,
                                company_name: item.company_name,
                            }
                        })
                        let defaultProps = {
                            options: companyData,
                            getOptionLabel: (option) => titleCase(option.company_name),
                        };
                        this.setState({ listCompany: defaultProps, company: companyData[0] }, () => {
                            this.getItemHierarki()
                        })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    getItemHierarki() {
        let payload = {
            "report_id": this.state.report.report_id,
            "company_id": this.state.company.company_id
        }
        api.create().getItemReportHierarki(payload).then((response) => {
            console.log(response.data)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        this.setState({ items: response.data.data, realItems: response.data.data})
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
            }
        })
    }

    handleCollapse(item) {
        let index = this.state.items.findIndex((val) => val.id === item.id)
        let items = this.state.items
        if (index == -1) {
            if (item.children.length > 0) {
                this.handleCollapse(item)
            }
        } else {
            items[index].collapse = !items[index].collapse
            console.log(items[index])
        }
    }

    onDefaultCollapsed = () => this.setState({
        defaultCollapsed: !this.state.defaultCollapsed
    });

    collapse = (collapseCase) => {
        let arrayCollapse = this.state.arrayCollapse
        let index = arrayCollapse.findIndex((val) => val.id === collapseCase)
        if (arrayCollapse.includes(collapseCase)) {
            arrayCollapse.splice(index, 1)
        } else {
            arrayCollapse.push(collapseCase)
        }
        if (this.refNestable) {
            this.refNestable.collapse(arrayCollapse.length > 0 ? arrayCollapse : 'NONE');
        }
    };

    handleSave() {
        let payload = {
            "item_report": this.state.items
        }
        if (JSON.stringify(this.state.items) === JSON.stringify(this.state.realItems)) {
            this.setState({ alert: true, messageAlert: 'Save visualization item report success!', tipeAlert: 'success' }, () => {
                setTimeout(() => {
                    this.props.onClickClose()
                }, 1000);
            })
        } else {
            api.create().saveVisualisasiReport(payload).then((response) => {
                console.log(response);
                // if (response.data.status == 'ucces') {
                if (response.data) {
                    if (response.ok) {
                        if (response.data.status === "success") {
                            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success' }, () => {
                                setTimeout(() => {
                                    this.props.onClickClose()
                                }, 1000);
                            })
                        } else {
                            this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                                if (response.data.message.includes("Someone Logged In")) {
                                    setTimeout(() => {
                                        localStorage.removeItem(Constant.TOKEN)
                                        window.location.reload();
                                    }, 1000);
                                }
                            })
                        }
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error' })
                    }
                } else {
                    this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error' })
                }
                // } else {
                // alert(response.data.message)
                // }
            })
        }
        
    }

    renderItem = ({ item, collapseIcon }) => {
        return (
            <div>
                <button type="button" onClick={() => this.collapse(item.id)}>{collapseIcon ? (this.state.arrayCollapse.includes(item.id) ? <AddIcon /> : <RemoveIcon />) : null}</button>
                <label style={{ marginLeft: collapseIcon ? 10 : 0 }}>{item.description}</label>
            </div>
        )
    };

    closeAlert() {
        this.setState({ alert: false })
    }

    render() {
        return (
            <div>
                <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                    <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                        {this.state.messageAlert}
                    </Alert>
                </Snackbar>
                <div style={{ height: this.props.height }}>
                    <div style={{ width: '100%' }} className={"main-color"} />
                    <div>
                        <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 25, paddingLeft: 25, marginTop: -118 }}>
                            <label style={{ color: 'white', width: '20%', fontSize: 16, paddingTop: 8 }}>Data Visualization</label>
                        </div>
                        <div style={{ padding: 25, width: '100%' }}>
                            <div style={{ width: '100%', padding: 25, backgroundColor: 'white', borderRadius: 6, border: 'solid 1px #c4c4c4' }}>
                                <label style={{ color: '#4b4b4b', fontSize: '16px', fontWeight: 'bold' }}>Reports Item Hierarchy</label>
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.listReport}
                                        id="report"
                                        onChange={(event, newInputValue) => this.setState({ report: newInputValue }, () => this.getItemHierarki())}
                                        debug
                                        disableClearable
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                label="Report Type"
                                                margin="normal"
                                                style={{ marginTop: 7 }}
                                                InputProps={{ ...params.InputProps, style: { width: "15%", fontSize: 11, fontFamily: 'Nunito Sans, sans-serif' } }}
                                            />}
                                        value={this.state.report}
                                    />
                                </div>
                                <div className="margin-top-10px" style={{ padding: 10, borderRadius: 5 }}>
                                    <Autocomplete
                                        {...this.state.listCompany}
                                        id="company"
                                        onChange={(event, newInputValue) => this.setState({ company: newInputValue }, () => this.getItemHierarki())}
                                        debug
                                        disableClearable
                                        renderInput={(params) =>
                                            <TextField {...params}
                                                label="Company"
                                                margin="normal"
                                                style={{ marginTop: 7 }}
                                                InputProps={{ ...params.InputProps, style: { width: "15%", fontSize: 11, fontFamily: 'Nunito Sans, sans-serif' } }}
                                            />}
                                        value={this.state.company}
                                    />
                                </div>
                                <div className="margin-top-30px">
                                    <Nestable
                                        items={this.state.items}
                                        collapsed={this.state.defaultCollapsed}
                                        renderItem={this.renderItem}
                                        ref={el => this.refNestable = el}
                                        onChange={(e) => this.setState({ items: e }, () => console.log(JSON.stringify(e)))}
                                    />
                                </div>
                            </div>
                        </div>
                        {/* <div className="row" style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingRight: 15, paddingLeft: 15, paddingBottom: 25 }}> */}
                            {/* <div onClick={() => this.props.onClickClose()} style={{ width: 102, height: 30, marginLeft: 25, backgroundColor: 'dodgerblue', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor: "pointer" }}>
                                <span style={{ color: '#fff', fontSize: 11 }}>Back</span>
                            </div> */}
                            {this.props.buttonEdit && (
                                <div className="row" style={{ float: 'right', marginRight: 25, paddingRight: 15, paddingLeft: 15, paddingBottom: 25}}>
                                    <div onClick={() => this.props.onClickClose()} style={{ width: 102, height: 30, border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor: "pointer" }}>
                                        <span style={{ color: '#354960', fontSize: 11 }}>Cancel</span>
                                    </div>
                                    <button onClick={() => {
                                        this.props.handleLoading() 
                                        this.props.scrollToTop()
                                        this.handleSave()}}>
                                        <div style={{ width: 102, height: 30, marginLeft: 25, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', cursor: "pointer" }}>
                                            <span style={{ color: '#fff', fontSize: 11 }}>Save</span>
                                        </div>
                                    </button>
                                </div>
                            )}
                        {/* </div> */}
                    </div>
                </div>
            </div>

        );
    }
}
