import React, { Component } from 'react';
import api from "../../api";
import Constant from "../../library/Constant";
import Images from "../../assets/Images";
import ReactTooltip from "react-tooltip";
import PropagateLoader from "react-spinners/PropagateLoader";
import { createMuiTheme, MuiThemeProvider, Snackbar } from "@material-ui/core";
import MUIDataTable from "mui-datatables";
import { withStyles } from "@material-ui/core/styles";
import MuiAlert from "@material-ui/lab/Alert";
import EditDocumentChcm from './EditDocumentChcm';
import PopUpDelete from "./PopUpDelete";

var ct = require("../../library/CustomTable");
const getMuiTheme = () => createMuiTheme(ct.customTable());
const options = ct.customOptionsManagementDocument();

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


export default class TableChcmDocument extends Component {

    constructor(props) {
        super(props)
        this.state = {
            dataTable: [],
            visibleCreate: false,
            refresh: '',
            alert: false,
            visibleEdit: false,
            popupDel: false,
        }
    }

    componentDidMount() {
        this.getData()
    }

    componentWillReceiveProps(props) {
        // console.log(props);
        const { refresh } = this.props;
        if (props.refresh !== refresh) {
            this.getData()
        }
    }

    getData() {
        let payload = {
            "submenu_id": this.props.submenu_id
        }
        this.setState({ loading: true })
        api.create().getChcmDocumentBySubmenu(payload).then(response => {
            // console.log("table document carfm");
            console.log(response)
            // console.log("table document carfm stop")
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        let dataTable = []
                        response.data.data.map((item, index) => {
                            let indexId = this.props.userCompActive.findIndex((val) => val == item.company_id)
                            if (indexId !== -1) {
                                dataTable.push([
                                    index,
                                    item.document_name,
                                    item.description,
                                    item.company_name,
                                    item.document_month,
                                    item.document_periode,
                                    item.document_type,
                                    String(Number(item.document_size) / 1000 + ' KB'),
                                    item.created_by,
                                    item.created_at,
                                    item.values,
                                    item.document_id,
                                ])
                            }
                        })

                        let docPath = response.data.data.map((item) => {
                            return [
                                item.document_filepath
                            ]
                        })

                        let docId = response.data.data.map((item) => {
                            return [
                                item.document_id
                            ]
                        })

                        // console.log(dataTable)
                        this.setState({ dataTable, docPath, docId, loading: false })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            if (response.data.message.includes("Someone Logged In") || response.data.message.includes("Token Expired")) {
                                setTimeout(() => {
                                    localStorage.removeItem(Constant.TOKEN)
                                    window.location.reload();
                                }, 1000);
                            }
                        })
                    }
                } else {
                    console.log("error di table document getcarfm 1");
                    this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'error', loading: false })
                }
            } else {
                console.log("error di table document getcarfm 2");
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    openPopUp = async (index, val, type) => {
        console.log(index);
        
        if (type === "download") {
            try {
                let url = `${process.env.REACT_APP_URL_MAIN_BE}/public/document/download_chcm_document?documentName=${this.state.docPath[val]}&&fileType=${index[6]}`;

                console.log("Fetching URL:", url); // Debugging step

                let response = await fetch(url);

                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }

                let blob = await response.blob();

                if (blob.size > 0) {
                    let downloadUrl = window.URL.createObjectURL(blob);
                    let a = document.createElement("a");
                    a.href = downloadUrl;
                    a.download =
                        (String(index[3]).includes(":")
                            ? String(index[3]).replace(":", " (") + ` )`
                            : String(index[3])) +
                        " - " +
                        index[4] +
                        " - " +
                        index[5] +
                        " - " +
                        index[1] +
                        "." +
                        index[6];
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                } else {
                    console.error("Downloaded file is empty.");
                }
            } catch (error) {
                console.error("Download error:", error);
            }
        }
        if (type === 'delete') {
            this.setState({
                id: this.state.docId[val],
                rowData: index,
                popupDel: true
            })
        }
        if (type === 'edit') {
            this.setState({
                id: this.state.docId[val],
                rowData: index,
                visibleEdit: true
            })
        }
    };

    deleteDoc = (payload) => {
        console.log(payload);

        this.setState({ popupDel: false, loading: true })
        api.create().deleteReportChcm(payload).then(response => {
            console.log(response.data)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status == 'success') {
                        this.getData()
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success', loading: false })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            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', loading: false })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

    updateDocument(payload) {
        console.log(payload);
        this.setState({ visibleEdit: false, loading: true })
        api.create().updateReportChcm(payload).then(response => {
            // console.log(response)
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === "success") {
                        this.getData()
                        this.setState({ konfirmasi: false, alert: true, messageAlert: response.data.message, tipeAlert: 'success', visibleEdit: false, loading: false })
                    } else {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'warning', loading: false }, () => {
                            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', loading: false })
                }
            } else {
                this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
            }
        })
    }

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

    render() {
        let columns = [{
            name: "Action",
            options: {
                filter: false,
                sort: false,
                customBodyRender: (val, tableMeta) => {
                    return (
                        <div style={{ display: 'flex' }}>

                            {this.props.btndownload && <a data-tip={'Download'} data-for="download">
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        marginRight: 15
                                    }}
                                    onClick={() => this.openPopUp(tableMeta.rowData, val, 'download')}
                                >
                                    <img src={Images.download} />
                                </button>
                            </a>}
                            {this.props.btnedit && <a data-tip={'Edit'} data-for="download">
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        marginRight: 15
                                    }}
                                    onClick={() => this.openPopUp(tableMeta.rowData, val, 'edit')}
                                >
                                    <img src={Images.editCopy} />
                                </button>
                            </a>}
                            {this.props.btndelete && <a data-tip={'Delete'} data-for="download">
                                <button
                                    style={{
                                        backgroundColor: 'transparent',
                                        cursor: 'pointer',
                                        borderColor: 'transparent',
                                        marginRight: 15
                                    }}
                                    onClick={() => this.openPopUp(tableMeta.rowData, val, 'delete')}
                                >
                                    <img src={Images.delete} />
                                </button>
                            </a>}
                            <ReactTooltip border={true} id="delete" place="bottom" type="light" effect="solid" />
                        </div >
                    );
                }
            }
        },
        {
            name: "File Name",
            options: {
                display: false
            }
        },
            "Description", "Company Name", "Period Month", "Period Year",
            "Type", "File Size", "Created By", "Created Date",
        {
            name: "Category",
            options: {
                display: false
            }
        },
        {
            name: "",
            options: {
                display: false
            }
        },
        ]

        const loadingComponent = (
            <div style={{ position: 'absolute', zIndex: 110, top: 0, left: 0, width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgba(255,255,255,0.8)' }}>
                <PropagateLoader
                    // css={override}
                    size={20}
                    color={"#274B80"}
                    loading={this.state.loading}
                />
            </div>
        );

        return (
            <div style={{ width: '100%' }}>
                {this.props.load && (
                    <div style={{ padding: 25 }}>
                        <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                            <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                                {this.state.messageAlert}
                            </Alert>
                        </Snackbar>
                        {this.state.loading && loadingComponent}
                        <MuiThemeProvider theme={getMuiTheme()}>
                            <MUIDataTable
                                // theme={getMuiTheme()}
                                data={this.state.dataTable}
                                columns={columns}
                                options={options}
                            />
                        </MuiThemeProvider>
                    </div>
                )}
                {this.state.visibleEdit && (
                    <EditDocumentChcm
                        type={"edit"}
                        onClickClose={() => this.setState({ visibleEdit: false })}
                        data={this.state.rowData}
                        idoc={this.state.id}
                        updateDocument={this.updateDocument.bind(this)}
                        menuName={this.props.menuName}
                        submenu_id={this.props.submenu_id}
                    />
                )}
                {this.state.popupDel && (
                    <PopUpDelete
                        type={"delete"}
                        onClickClose={() => this.setState({ popupDel: false })}
                        data={this.state.rowData}
                        idoc={this.state.id}
                        // getList={() => this.getData.bind(this)}
                        deleteDoc={this.deleteDoc.bind(this)}
                    />
                )}
            </div>
        )
    }
}

