import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { TextField, List, ListSubheader, Typography, Collapse } 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';

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


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: [
                {
                    id: 0, GG: 'Accumulated Depreciation (negative value)', collapse: false,
                    children: [
                        { id: 3, GG: 'Beginning Balance', collapse: false },
                        { id: 4, GG: 'Depreciation expense MTD (please fill in, if any)', collapse: false },
                        { id: 5, GG: 'Depreciation expense MTD (please fill in, if any)', collapse: false }
                    ]
                }, {
                    id: 1, GG: 'Control Gain/(Loss) on Fixed Assets', collapse: false
                }, {
                    id: 2, GG: 'Gain/(Loss) on Fixed Assets', collapse: false,
                    children: [
                        {
                            id: 6, GG: 'NBV', collapse: false,
                            children: [
                                { id: 8, GG: 'Cost', collapse: false },
                                { id: 9, GG: 'Accm. Depreciation', collapse: false },
                            ]
                        },
                        { id: 7, GG: 'Proceed from sale or disposal of Fixed Assets (please fill in, if any)', collapse: false },
                    ]
                },
            ],
            arrayCollapse: [],
            defaultCollapsed: false,
            listReport: null,
            report: null,
            listCompany: null,
            company: null
        }
    }

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

    getReportType() {
        api.create().getReportType().then((response) => {
            this.getCompanyActive()
            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 {
                alert(response.data.message)
            }
        })
    }

    getCompanyActive() {
        api.create().getPerusahaanActive().then((response) => {
            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 {
                alert(response.data.message)
            }
        })
    }

    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.data.status == 'success') {
                    this.setState({ items: response.data.data })
                }
            }
        })
    }

    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
        }
        api.create().saveVisualisasiReport(payload).then((response) => {
            // if (response.data.status == 'ucces') {
            this.props.onClickClose()
            // } 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.report_name}</label>
            </div>
        )
    };

    render() {
        return (
            <div>
                <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: -150 }}>
                            <label style={{ color: 'white', width: '20%', fontSize: 16, paddingTop: 8 }}>Visualisasi Data</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' }}>Hirarki Item Laporan</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="Jenis Laporan" margin="normal" style={{ marginTop: 7 }} />}
                                        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 }} />}
                                        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 }}>Kembali</span>
                            </div>
                            <div className="row" style={{ float: 'right', marginRight: 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 }} >Batal</span>
                                </div>
                                <button onClick={() => 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 }}>Simpan</span>
                                    </div>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        );
    }
}