import React, { Component } from 'react';
import { Container, Row, Col } from "react-bootstrap";
import { Typography, withStyles, Snackbar } from '@material-ui/core';
import Perusahaan from "./Company";
import MuiAlert from '@material-ui/lab/Alert';
import Nestable from 'react-nestable/dist/Nestable';
import AddIcon from '@material-ui/icons/Add';
import RemoveIcon from '@material-ui/icons/Remove';
import api from '../../../api';
import Constant from '../../../library/Constant';

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

export default class VisualPerusahaan extends Component {
    constructor(props) {
        super(props)
        this.state = {
            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,
            alert: false,
            tipeAlert: '',
            messageAlert: '',
        }
    }

    componentDidMount() {
        this.getPerusahaan()
    }

    getPerusahaan() {
        api.create().getPerusahaanHierarki().then((response) => {
            console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        this.setState({ items: response.data.data })
                        console.log(response.data.data)
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                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' })
            }
        })
    }

    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 = {
            "company": this.state.items
        }
        this.props.updateHierarchy(payload)
        /* api.create().saveVisualisasiPerusahaan(payload).then((response) => {
            // console.log(response.data)
            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()
                                window.location.reload();
                            }, 1000);
                        })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning' }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                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.company_name}</label>
            </div>
        )
    };

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

    render() {

        return (
            <div>
                <div style={{ height: this.props.height }}>
                    <div style={{ width: '100%', backgroundColor: '#354960' }} />
                    <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 }}>Company Hierarchy</label>
                        </div>
                        <div style={{ display: 'flex', paddingRight: 25, paddingLeft: 25 }}>
                            <label style={{ color: '#51c6ea', width: '20%', fontSize: 11 }}>Master Data / Company /
                                    <span style={{ color: 'white', width: '20%', fontSize: 11 }}> Visualization</span>
                            </label>
                        </div>
                        <div style={{ padding: 25, width: '100%' }}>
                            <div style={{ width: '100%', padding: 25, backgroundColor: 'white', borderRadius: 6, border: 'solid 1px #c4c4c4' }}>
                                <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 className="row" style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', float: 'right', 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 }}>
                                    <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>
                                    <div onClick={() => {
                                        this.props.handleLoading()
                                        this.handleSave()
                                        }} 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>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>

        );
    }
}
