import React, { Component, useRef } from 'react';
import { Typography, Paper, TextField, Snackbar, withStyles, Switch, FormControlLabel } from '@material-ui/core';
import Images from '../../assets/Images';
import Constant from '../../library/Constant';
import api from '../../api';
import { PropagateLoader } from 'react-spinners';
import { format } from 'date-fns';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { Alert } from '@material-ui/lab';
import ReactTooltip from "react-tooltip";
import SunEditor, { buttonList } from "suneditor-react";
import 'suneditor/dist/css/suneditor.min.css'; // Import Sun Editor's CSS File


const IOSSwitch = withStyles((theme) => ({
    root: {
        width: 55,
        height: 31,
        padding: 0,
        margin: theme.spacing(1),
    },
    switchBase: {
        padding: 3,
        marginLeft: 1,
        '&$checked': {
            transform: 'translateX(16px)',
            color: theme.palette.common.white,
            paddingLeft: 11,
            '& + $track': {
                backgroundColor: '#52d869',
                opacity: 1,
                border: 'none',
            },
        },
        '&$focusVisible $thumb': {
            color: '#52d869',
            border: '6px solid #fff',
        },
    },
    thumb: {
        width: 25,
        height: 25,
    },
    track: {
        borderRadius: 30 / 2,
        border: `1px solid ${theme.palette.grey[400]}`,
        backgroundColor: 'red',
        opacity: 1,
        transition: theme.transitions.create(['background-color', 'border']),
    },
    checked: {},
    focusVisible: {},
}))(({ classes, ...props }) => {
    return (
        <Switch
            focusVisibleClassName={classes.focusVisible}
            disableRipple
            classes={{
                root: classes.root,
                switchBase: classes.switchBase,
                thumb: classes.thumb,
                track: classes.track,
                checked: classes.checked,
            }}
            {...props}
        />
    );
});


class MaintenanceMode extends Component {
    constructor(props) {
        super(props)
        this.editorRef = React.createRef();
        this.editorRefEmail = React.createRef();
        this.editorRefContent = React.createRef();
        // this.handleChange = this.handleChange.bind(this)
        this.state = {
            load: false,
            loading: false,
            mailcontentModeActive: "",
            mailcontentModeNonActive: "",
            checkedB: true,
            headline: '',
            maintenanceContent: "",
            subjectMailActive: '',
            subjectMailNonActive: '',
            maintenanceID: null,
            maintenanceStatus: 0,
            mailStatusActive: 0,
            mailStatusNonActive: 0,


        }
    }


    componentDidMount() {
        this.getDetailMaintenanceMode()
    }

    getDetailMaintenanceMode() {
        this.setState({ loading: true })
        api.create().getDetailMaintenanceMode().then((response) => {
            console.log(response);
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        let data = response.data.data
                        console.log(data.maintenance_mail.length);
                        let dataModeActive = data.maintenance_mail.length > 0 ? data.maintenance_mail.[0].[0] : null
                        let dataModeNonActive = data.maintenance_mail.length > 0 ? data.maintenance_mail.[0].[1] : null
                        this.setState({
                            maintenanceID: data.maintenance_id,
                            headline: data.maintenance_headline,
                            maintenanceContent: data.maintenance_content,
                            maintenanceStatus: data.maintenance_status === null ? 0 : data.maintenance_status,
                            mailStatusActive: dataModeActive === null ? 0 : dataModeActive.status,
                            subjectMailActive: dataModeActive === null ? null : dataModeActive.mailSubject,
                            mailcontentModeActive: dataModeActive === null ? null : dataModeActive.mailBody,
                            mailStatusNonActive: dataModeNonActive === null ? 0 : dataModeNonActive.status,
                            subjectMailNonActive: dataModeNonActive === null ? null : dataModeNonActive.mailSubject,
                            mailcontentModeNonActive: dataModeNonActive === null ? null : dataModeNonActive.mailBody,

                        }, () => {
                            setTimeout(() => {
                                this.setState({ loading: false })
                            }, 2000);
                        })
                    } 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' })
            }
        })
    }

    handleChange(e, type) {
        let data = this.state
        let isDate = type !== '' ? true : false
        if (isDate && type === 'start_date') {
            this.setState({
                ...data, startDate: format(e, 'yyyy-MM-dd'), endDate: null
            })
        } else if (isDate && type === 'end_date') {
            this.setState({
                ...data, endDate: format(e, 'yyyy-MM-dd')
            })
        } else {
            this.setState({
                ...data, [e.target.name]: e.target.value
            })
        }

    }

    handleCreate() {
        let bodyInactive = '<p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Hi,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">We’re happy to let you know that TIA 4.0 is back online!</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">We appreciate your patience and kind understanding.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Thank you!</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Regards,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong><span style="font-size: 13px"><span style="color: rgb(0, 32, 96)">Triputra Group</span></span></strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>&nbsp;</strong></span></span></p><div class="se-component se-image-container __se__float-" contenteditable="false"><figure style="margin: 0px; width: 288px;"><img alt="" src="https://ci3.googleusercontent.com/proxy/pZlDMYsSIvwgrUzQ7hPn1nrk26YNIJbCPH_G8X56UqyPfO3tJ2BX1RFFZ7tTlXkJa7ccfzn7CVm6zWmbgFyhVkvTBjAAHzaAo3sllX9kkd9aQnnk=s0-d-e1-ft#https://www.triputra-group.com/mt-content/uploads/images/logo.png" data-origin="288,64" data-proportion="true" data-size="288px,64px" data-align="" data-file-name="logo.png" data-file-size="0" origin-size="288,64" style="width: 288px; height: 64px;" data-index="0"></figure></div><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Menara Kadin Indonesia, 23<sup>rd</sup>&nbsp;Floor</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Jl. HR Rasuna Said Blok X-5, Kav 2-3, Kuningan, Jakarta Selatan 12950</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Ph&nbsp;<a href="callto:+62%2021%205274323" target="_blank">+62 21 5274323</a>;&nbsp;<a href="http://www.triputra-group.com/" target="_blank" class="on">www.triputra-group.com</a></strong></span></span></p>'
        let bodyActive = '<p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Hi,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><span style="font-size: 29px">TIA 4.0 is down for maintenance!</span></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Thank you for your patience, we expect to be back shortly.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">We apologize for any inconvenience.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">For more information, please contact our email:&nbsp;<span style="color: rgb(0, 90, 149)"><a href="mailto:tia4.0@triputra-group.com" target="_blank">tia4.0@triputra-group.com</a></span>.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Regards,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong><span style="font-size: 13px"><span style="color: rgb(0, 32, 96)">Triputra Group</span></span></strong></span></span></p><div class="se-component se-image-container __se__float-" contenteditable="false"><figure style="margin: 0px; width: 288px;"><img alt="" src="https://www.triputra-group.com/mt-content/uploads/images/logo.png" data-origin="288,64" data-proportion="true" data-size="288px,64px" data-align="" data-file-name="logo.png" data-file-size="0" origin-size="288,64" style="width: 288px; height: 64px;" data-index="0"></figure></div><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Menara Kadin Indonesia, 23<sup>rd</sup>&nbsp;Floor</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Jl. HR Rasuna Said Blok X-5, Kav 2-3, Kuningan, Jakarta Selatan 12950</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Ph&nbsp;<a href="callto:+62 21 5274323">+62 21 5274323</a>;&nbsp;<a href="http://www.triputra-group.com/" target="_blank">www.triputra-group.com</a></strong></span></span></p>'

        let payload = {
            "maintenance_headline": this.state.headline,
            "maintenance_content": this.state.maintenanceContent,
            "maintenance_status": this.state.maintenanceStatus,
            "maintenance_mail": [
                {
                    "mail_type": "MAINTENANCE_MODE_ACTIVE",
                    "mail_subject": "TIA 4.0 Is Under Maintenance",
                    "mail_body": bodyActive,
                    "mail_status": 0
                },
                {
                    "mail_type": "MAINTENANCE_MODE_INACTIVE",
                    "mail_subject": "TIA 4.0 is Back",
                    "mail_body": bodyInactive,
                    "mail_status": 1
                }
            ]
            // "maintenance_mail": [
            //     {
            //         "mail_type": "MAINTENANCE_MODE_ACTIVE",
            //         "mail_subject": this.state.subjectMailActive,
            //         "mail_body": this.state.mailcontentModeActive,
            //         "mail_status": this.state.mailStatusActive
            //     },
            //     {
            //         "mail_type": "MAINTENANCE_MODE_INACTIVE",
            //         "mail_subject": this.state.subjectMailNonActive,
            //         "mail_body": this.state.mailcontentModeNonActive,
            //         "mail_status": this.state.mailStatusNonActive
            //     }
            // ]
        }
        console.log(payload);
        api.create().createMaintenanceMode(payload).then((response) => {
            console.log(response)
            this.setState({ loading: true })
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success', loading: false }, () => this.getDetailMaintenanceMode())
                    } 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', loading: false })
                }
            } else {
                // this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
                alert(response.problem)
                this.setState({ loading: false })
            }
        })

    }

    handleEdit() {
        let bodyInactive = '<p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Hi,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">We’re happy to let you know that TIA 4.0 is back online!</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">We appreciate your patience and kind understanding.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Thank you!</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Regards,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong><span style="font-size: 13px"><span style="color: rgb(0, 32, 96)">Triputra Group</span></span></strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>&nbsp;</strong></span></span></p><div class="se-component se-image-container __se__float-" contenteditable="false"><figure style="margin: 0px; width: 288px;"><img alt="" src="https://ci3.googleusercontent.com/proxy/pZlDMYsSIvwgrUzQ7hPn1nrk26YNIJbCPH_G8X56UqyPfO3tJ2BX1RFFZ7tTlXkJa7ccfzn7CVm6zWmbgFyhVkvTBjAAHzaAo3sllX9kkd9aQnnk=s0-d-e1-ft#https://www.triputra-group.com/mt-content/uploads/images/logo.png" data-origin="288,64" data-proportion="true" data-size="288px,64px" data-align="" data-file-name="logo.png" data-file-size="0" origin-size="288,64" style="width: 288px; height: 64px;" data-index="0"></figure></div><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Menara Kadin Indonesia, 23<sup>rd</sup>&nbsp;Floor</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Jl. HR Rasuna Said Blok X-5, Kav 2-3, Kuningan, Jakarta Selatan 12950</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Ph&nbsp;<a href="callto:+62%2021%205274323" target="_blank">+62 21 5274323</a>;&nbsp;<a href="http://www.triputra-group.com/" target="_blank" class="on">www.triputra-group.com</a></strong></span></span></p>'
        let bodyActive = '<p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Hi,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><span style="font-size: 29px">TIA 4.0 is down for maintenance!</span></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Thank you for your patience, we expect to be back shortly.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">We apologize for any inconvenience.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">For more information, please contact our email:&nbsp;<span style="color: rgb(0, 90, 149)"><a href="mailto:tia4.0@triputra-group.com" target="_blank">tia4.0@triputra-group.com</a></span>.</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">Regards,</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong><span style="font-size: 13px"><span style="color: rgb(0, 32, 96)">Triputra Group</span></span></strong></span></span></p><div class="se-component se-image-container __se__float-" contenteditable="false"><figure style="margin: 0px; width: 288px;"><img alt="" src="https://www.triputra-group.com/mt-content/uploads/images/logo.png" data-origin="288,64" data-proportion="true" data-size="288px,64px" data-align="" data-file-name="logo.png" data-file-size="0" origin-size="288,64" style="width: 288px; height: 64px;" data-index="0"></figure></div><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)">&nbsp;</span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Menara Kadin Indonesia, 23<sup>rd</sup>&nbsp;Floor</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Jl. HR Rasuna Said Blok X-5, Kav 2-3, Kuningan, Jakarta Selatan 12950</strong></span></span></p><p><span style="font-size: 15px"><span style="color: rgb(0, 0, 0)"><strong>Ph&nbsp;<a href="callto:+62 21 5274323">+62 21 5274323</a>;&nbsp;<a href="http://www.triputra-group.com/" target="_blank">www.triputra-group.com</a></strong></span></span></p>'

        let payload = {
            "maintenance_id": this.state.maintenanceID,
            "maintenance_headline": this.state.headline,
            "maintenance_content": this.state.maintenanceContent,
            "maintenance_status": this.state.maintenanceStatus,
            "maintenance_mail": [
                {
                    "mail_type": "MAINTENANCE_MODE_ACTIVE",
                    "mail_subject": "TIA 4.0 Is Under Maintenance",
                    "mail_body": bodyActive,
                    "mail_status": 0
                },
                {
                    "mail_type": "MAINTENANCE_MODE_INACTIVE",
                    "mail_subject": "TIA 4.0 is Back",
                    "mail_body": bodyInactive,
                    "mail_status": 1
                }
            ]
            // "maintenance_mail": [
            //     {
            //         "mail_type": "MAINTENANCE_MODE_ACTIVE",
            //         "mail_subject": this.state.subjectMailActive,
            //         "mail_body": this.state.mailcontentModeActive,
            //         "mail_status": this.state.mailStatusActive
            //     },
            //     {
            //         "mail_type": "MAINTENANCE_MODE_INACTIVE",
            //         "mail_subject": this.state.subjectMailNonActive,
            //         "mail_body": this.state.mailcontentModeNonActive,
            //         "mail_status": this.state.mailStatusNonActive
            //     }
            // ]
        }
        console.log(payload);
        api.create().updateMaintenanceMode(payload).then((response) => {
            console.log(response)
            this.setState({ loading: true })
            if (response.data) {
                if (response.ok) {
                    if (response.data.status === 'success') {
                        this.setState({ alert: true, messageAlert: response.data.message, tipeAlert: 'success', loading: false }, () => this.getDetailMaintenanceMode())
                    } 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', loading: false })
                }
            } else {
                // this.setState({ alert: true, messageAlert: response.problem, tipeAlert: 'error', loading: false })
                alert(response.problem)
                this.setState({ loading: false })
            }
        })
    }

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

    // handleChange(event) {
    //     this.setState({ ...this.state.checkedB, [event.target.name]: event.target.checked });
    // };

    handleImageUploadBefore(files, info, uploadHandler) {
        // uploadHandler is a function
        console.log(files, info, uploadHandler)
        try {
            this.ResizeImage(files, uploadHandler)
        } catch (err) {
            uploadHandler(err.toString())
        }
    }
    handleImageUpload(targetImgElement, index, state, imageInfo, remainingFilesCount) {
        console.log(targetImgElement, index, state, imageInfo, remainingFilesCount)
    }

    handleImageUploadError(errorMessage, result) {
        console.log(errorMessage, result)
    }

    handleEditorChange(value) {
        // console.log(value);
        this.setState({ mailcontentModeActive: value })

        // setContent(value)
    }

    handleDrop(event) {
        console.log(event); //Get the drop event
    }

    handleBlur(event, editorContents) {
        console.log(event, editorContents); //Get the blur event
    }

    imageUploadHandler(xmlHttpRequest, info, core) {
        console.log(xmlHttpRequest, info, core)
    }

    ResizeImage(files, uploadHandler) {
        const uploadFile = files[0];
        const img = document.createElement('img');
        const canvas = document.createElement('canvas');
        const reader = new FileReader();

        console.log(uploadFile);

        reader.onload = function (e) {
            img.src = e.target.result
            img.onload = function () {
                let ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);

                const MAX_WIDTH = 200;
                const MAX_HEIGHT = 100;
                let width = img.width;
                let height = img.height;

                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }

                canvas.width = width;
                canvas.height = height;

                ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, width, height);

                canvas.toBlob(function (blob) {
                    uploadHandler([new File([blob], uploadFile.name)])
                }, uploadFile.type, 1);
            }
        }

        reader.readAsDataURL(uploadFile);
    }

    handleImageUploadBeforeEmail(files, info, uploadHandler) {
        // uploadHandler is a function
        console.log(files, info, uploadHandler)
        try {
            this.ResizeImageEmail(files, uploadHandler)
        } catch (err) {
            uploadHandler(err.toString())
        }
    }
    handleImageUploadEmail(targetImgElement, index, state, imageInfo, remainingFilesCount) {
        console.log(targetImgElement, index, state, imageInfo, remainingFilesCount)
    }

    handleImageUploadErrorEmail(errorMessage, result) {
        console.log(errorMessage, result)
    }

    handleEditorChangeEmail(value) {
        // console.log(value);
        this.setState({ mailcontentModeNonActive: value })

        // setContent(value)
    }

    handleDropEmail(event) {
        console.log(event); //Get the drop event
    }

    handleBlurEmail(event, editorContents) {
        console.log(event, editorContents); //Get the blur event
    }

    imageUploadHandlerEmail(xmlHttpRequest, info, core) {
        console.log(xmlHttpRequest, info, core)
    }

    ResizeImageEmail(files, uploadHandler) {
        const uploadFile = files[0];
        const img = document.createElement('img');
        const canvas = document.createElement('canvas');
        const reader = new FileReader();

        console.log(uploadFile);

        reader.onload = function (e) {
            img.src = e.target.result
            img.onload = function () {
                let ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);

                const MAX_WIDTH = 200;
                const MAX_HEIGHT = 100;
                let width = img.width;
                let height = img.height;

                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }

                canvas.width = width;
                canvas.height = height;

                ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, width, height);

                canvas.toBlob(function (blob) {
                    uploadHandler([new File([blob], uploadFile.name)])
                }, uploadFile.type, 1);
            }
        }

        reader.readAsDataURL(uploadFile);
    }

    handleImageUploadBeforeContent(files, info, uploadHandler) {
        // uploadHandler is a function
        console.log(files, info, uploadHandler)
        try {
            this.ResizeImage(files, uploadHandler)
        } catch (err) {
            uploadHandler(err.toString())
        }
    }
    handleImageUploadContent(targetImgElement, index, state, imageInfo, remainingFilesCount) {
        console.log(targetImgElement, index, state, imageInfo, remainingFilesCount)
    }

    handleImageUploadErrorContent(errorMessage, result) {
        console.log(errorMessage, result)
    }

    handleEditorChangeContent(value) {
        // console.log(value);
        this.setState({ maintenanceContent: value })

        // setContent(value)
    }

    handleDropContent(event) {
        console.log(event); //Get the drop event
    }

    handleBlurContent(event, editorContents) {
        console.log(event, editorContents); //Get the blur event
    }

    imageUploadHandlerContent(xmlHttpRequest, info, core) {
        console.log(xmlHttpRequest, info, core)
    }

    ResizeImageContent(files, uploadHandler) {
        const uploadFile = files[0];
        const img = document.createElement('img');
        const canvas = document.createElement('canvas');
        const reader = new FileReader();

        console.log(uploadFile);

        reader.onload = function (e) {
            img.src = e.target.result
            img.onload = function () {
                let ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);

                const MAX_WIDTH = 200;
                const MAX_HEIGHT = 100;
                let width = img.width;
                let height = img.height;

                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }

                canvas.width = width;
                canvas.height = height;

                ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, width, height);

                canvas.toBlob(function (blob) {
                    uploadHandler([new File([blob], uploadFile.name)])
                }, uploadFile.type, 1);
            }
        }

        reader.readAsDataURL(uploadFile);
    }

    render() {

        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={{ flex: 1, backgroundColor: '#f8f8f8', minHeight: this.props.height }}>
                <Snackbar open={this.state.alert} autoHideDuration={6000} onClose={() => this.closeAlert()}>
                    <Alert onClose={() => this.closeAlert()} severity={this.state.tipeAlert}>
                        {this.state.messageAlert}
                    </Alert>
                </Snackbar>
                <div>
                    {this.state.loading && loadingComponent}
                    <div className={"main-color"} style={{ height: 78, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
                        <Typography style={{ fontSize: '16px', color: 'white' }}>Maintenance Mode</Typography>
                    </div>
                    <div style={{ padding: 20, width: '100%' }}>
                        <Paper style={{ paddingTop: 10, paddingBottom: 50 }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', margin: 10, borderBottom: 'solid 2px #00000057', height: '100%' }}>
                                <div >
                                    <Typography style={{ fontSize: '17px', color: '#4b4b4b', margin: 10 }}>General Setting - Maintenance Mode</Typography>
                                </div>
                                <div style={{ marginTop: 5, marginRight: 30 }}>
                                    {/* <button
                                        type="button"
                                        style={{ background: 'white' }}
                                        onClick={() => Alert('Coming Soon !')}
                                    >
                                        <div style={{ width: 102, height: 30, backgroundColor: '#fff', border: 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center', marginRight: 15 }}>
                                            <span style={{ color: '#354960', fontSize: 11 }}>Batal</span>
                                        </div>
                                    </button> */}
                                    <button
                                        type="button"
                                        onClick={() => this.state.maintenanceID === null ? this.handleCreate() : this.handleEdit()}
                                    >
                                        <div style={{ width: 102, height: 30, backgroundColor: '#354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                            <span style={{ color: '#fff', fontSize: 11 }}>Simpan</span>
                                        </div>
                                    </button>
                                </div>
                            </div>
                            <div style={{ margin: 20 }}>
                                <div style={{ display: 'flex', marginTop: 20, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Maintenance Mode</Typography>
                                    <div style={{ width: '80%', paddingTop: 10 }}>
                                        <div>
                                            {/* <FormControlLabel
                                                control={<IOSSwitch checked={this.state.checkedB} onChange={this.handleChange.bind(this)} name="checkedB" />} /> */}
                                            <button
                                                type="button"
                                                style={{ background: '#fff', marginRight: 15 }}
                                                onClick={() => this.setState({ maintenanceStatus: 0 })}
                                            >
                                                <div style={{ width: 102, height: 30, backgroundColor: this.state.maintenanceStatus === 0 ? 'green' : '#fff', border: this.state.maintenanceStatus === 0 ? 'none' : 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                    <span style={{ color: this.state.maintenanceStatus === 0 ? 'white' : '#354960', fontSize: 11, fontWeight: 'bold' }}>Non Active</span>
                                                </div>
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => this.setState({ maintenanceStatus: 1 })}
                                            >
                                                <div style={{ width: 102, height: 30, backgroundColor: this.state.maintenanceStatus === 1 ? 'red' : '#fff', border: this.state.maintenanceStatus === 1 ? null : 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                    <span style={{ color: this.state.maintenanceStatus === 1 ? 'white' : '#354960', fontSize: 11, fontWeight: 'bold' }}>Active</span>
                                                </div>
                                            </button>
                                        </div>
                                        <Typography style={{ alignSelf: 'center', width: '80%', marginTop: 11, color: '#656565', fontSize: 14 }}>Dengan mengaktifkan, maka user selain admin tidak dapat melakukan akses ke dalam sistem. (Halaman maintenance terbuka)</Typography>
                                    </div>
                                </div>
                                <Typography style={{ marginTop: 20, width: '80%', color: '#656565', fontSize: 15, fontWeight: 'bold' }}>Setting Halaman Maintenance</Typography>
                                <div style={{ display: 'flex', marginTop: 15, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Headline</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div>
                                            <TextField
                                                variant="outlined"
                                                id="headline"
                                                name="headline"
                                                value={this.state.headline}
                                                onChange={(e) => this.handleChange(e, '')}
                                                style={{ width: '80%' }}
                                                inputProps={{ style: { color: '#656565', height: 0 } }}
                                            />
                                        </div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', marginTop: 15, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Content</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div style={{ marginTop: 20 }}>
                                            <SunEditor
                                                showToolbar={true}
                                                enableToolbar={true}
                                                ref={this.editorRefContent}
                                                width={"100%"}
                                                setOptions={{
                                                    width: '80%',
                                                    height: 300,
                                                    buttonList: [
                                                        // default
                                                        ['undo', 'redo'],
                                                        ['font', 'fontSize', 'formatBlock'],
                                                        ['paragraphStyle', 'blockquote'],
                                                        ['fontColor', 'hiliteColor', 'textStyle'],
                                                        ['bold', 'underline', 'italic', 'list', 'align'],
                                                        ['table', 'link', 'image'],
                                                        ['fullScreen']
                                                    ]
                                                    // buttonList: buttonList.formatting // Or Array of button list, eg. [['font', 'align'], ['image']]
                                                    // Other option
                                                }}
                                                onChange={this.handleEditorChangeContent.bind(this)}
                                                setContents={this.state.maintenanceContent}
                                                onDrop={this.handleDropContent.bind(this)}
                                                imageUploadHandler={this.imageUploadHandlerContent.bind(this)}
                                                onBlur={this.handleBlurContent.bind(this)}
                                                onImageUploadBefore={this.handleImageUploadBeforeContent.bind(this)}
                                                onImageUpload={this.handleImageUploadContent.bind(this)}
                                                onImageUploadError={this.handleImageUploadErrorContent.bind(this)}
                                            />
                                        </div>
                                    </div>
                                </div>
                                {/* <Typography style={{ marginTop: 30, width: '80%', color: '#656565', fontSize: 15, fontWeight: 'bold' }}>Setting Notifikasi Email Saat Maintenance Mode Aktif</Typography>
                                <div style={{ display: 'flex', marginTop: 20, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Kirim Email Notif</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div>
                                            <button
                                                type="button"
                                                style={{ background: '#fff', marginRight: 15 }}
                                                onClick={() => this.setState({ mailStatusActive: 0 })}
                                            >
                                                <div style={{ width: 102, height: 30, backgroundColor: this.state.mailStatusActive === 0 ? 'red' : '#fff', border: this.state.mailStatusActive === 0 ? 'none' : 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                    <span style={{ color: this.state.mailStatusActive === 0 ? 'white' : '#354960', fontSize: 11, fontWeight: 'bold' }}>Tidak</span>
                                                </div>
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => this.setState({ mailStatusActive: 1 })}
                                            >
                                                <div style={{ width: 102, height: 30, backgroundColor: this.state.mailStatusActive === 1 ? 'green' : '#fff', border: this.state.mailStatusActive === 1 ? null : 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                    <span style={{ color: this.state.mailStatusActive === 1 ? 'white' : '#354960', fontSize: 11, fontWeight: 'bold' }}>Ya</span>
                                                </div>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', marginTop: 15, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Subject Email</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div>
                                            <TextField
                                                variant="outlined"
                                                id="subjectMailActive"
                                                name="subjectMailActive"
                                                onChange={(e) => this.handleChange(e, '')}
                                                value={this.state.subjectMailActive}
                                                style={{ width: '80%' }}
                                                inputProps={{ style: { color: '#656565', height: 0 } }}
                                            />
                                        </div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', marginTop: 15, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Content Email</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div style={{ marginTop: 20 }}>
                                            <SunEditor
                                                showToolbar={true}
                                                enableToolbar={true}
                                                ref={this.editorRef}
                                                width={"100%"}
                                                setOptions={{
                                                    width: '80%',
                                                    height: 300,
                                                    buttonList: [
                                                        // default
                                                        ['undo', 'redo'],
                                                        ['font', 'fontSize', 'formatBlock'],
                                                        ['paragraphStyle', 'blockquote'],
                                                        ['fontColor', 'hiliteColor', 'textStyle'],
                                                        ['bold', 'underline', 'italic', 'list', 'align'],
                                                        ['table', 'link', 'image'],
                                                        ['fullScreen']
                                                    ]
                                                    // buttonList: buttonList.formatting // Or Array of button list, eg. [['font', 'align'], ['image']]
                                                    // Other option
                                                }}
                                                onChange={this.handleEditorChange.bind(this)}
                                                setContents={this.state.mailcontentModeActive}
                                                onDrop={this.handleDrop.bind(this)}
                                                imageUploadHandler={this.imageUploadHandler.bind(this)}
                                                onBlur={this.handleBlur.bind(this)}
                                                onImageUploadBefore={this.handleImageUploadBefore.bind(this)}
                                                onImageUpload={this.handleImageUpload.bind(this)}
                                                onImageUploadError={this.handleImageUploadError.bind(this)}
                                            />
                                        </div>
                                    </div>
                                </div> */}
                                {/* <Typography style={{ marginTop: 30, width: '80%', color: '#656565', fontSize: 15, fontWeight: 'bold' }}>Setting Notifikasi Email Saat Maintenance Mode Non Aktif</Typography>
                                <div style={{ display: 'flex', marginTop: 20, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Kirim Email Notif</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div>
                                            <button
                                                type="button"
                                                style={{ background: '#fff', marginRight: 15 }}
                                                onClick={() => this.setState({ mailStatusNonActive: 0 })}
                                            >
                                                <div style={{ width: 102, height: 30, backgroundColor: this.state.mailStatusNonActive === 0 ? 'red' : '#fff', border: this.state.mailStatusNonActive === 0 ? 'none' : 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                    <span style={{ color: this.state.mailStatusNonActive === 0 ? 'white' : '#354960', fontSize: 11, fontWeight: 'bold' }}>Tidak</span>
                                                </div>
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => this.setState({ mailStatusNonActive: 1 })}
                                            >
                                                <div style={{ width: 102, height: 30, backgroundColor: this.state.mailStatusNonActive === 1 ? 'green' : '#fff', border: this.state.mailStatusNonActive === 1 ? null : 'solid 1px #354960', borderRadius: 5, alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
                                                    <span style={{ color: this.state.mailStatusNonActive === 1 ? 'white' : '#354960', fontSize: 11, fontWeight: 'bold' }}>Ya</span>
                                                </div>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', marginTop: 15, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Subject Email</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div>
                                            <TextField
                                                variant="outlined"
                                                id="subjectMailNonActive"
                                                name="subjectMailNonActive"
                                                onChange={(e) => this.handleChange(e, '')}
                                                value={this.state.subjectMailNonActive}
                                                style={{ width: '80%' }}
                                                inputProps={{ style: { color: '#656565', height: 0 } }}
                                            />
                                        </div>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', marginTop: 15, width: '100%', justifyContent: 'space-between' }}>
                                    <Typography style={{ marginTop: 13, width: '20%', color: '#656565', fontSize: 14 }}>Content Email</Typography>
                                    <div style={{ width: '80%', margin: 0, marginTop: 10 }}>
                                        <div style={{ marginTop: 20 }}>
                                            <SunEditor
                                                showToolbar={true}
                                                enableToolbar={true}
                                                ref={this.editorRefEmail}
                                                width={"100%"}
                                                setOptions={{
                                                    width: '80%',
                                                    height: 300,
                                                    buttonList: [
                                                        // default
                                                        ['undo', 'redo'],
                                                        ['font', 'fontSize', 'formatBlock'],
                                                        ['paragraphStyle', 'blockquote'],
                                                        ['fontColor', 'hiliteColor', 'textStyle'],
                                                        ['bold', 'underline', 'italic', 'list', 'align'],
                                                        ['table', 'link', 'image'],
                                                        ['fullScreen']
                                                    ]
                                                    // buttonList: buttonList.formatting // Or Array of button list, eg. [['font', 'align'], ['image']]
                                                    // Other option
                                                }}
                                                onChange={this.handleEditorChangeEmail.bind(this)}
                                                setContents={this.state.mailcontentModeNonActive}
                                                onDrop={this.handleDropEmail.bind(this)}
                                                imageUploadHandler={this.imageUploadHandlerEmail.bind(this)}
                                                onBlur={this.handleBlurEmail.bind(this)}
                                                onImageUploadBefore={this.handleImageUploadBeforeEmail.bind(this)}
                                                onImageUpload={this.handleImageUploadEmail.bind(this)}
                                                onImageUploadError={this.handleImageUploadErrorEmail.bind(this)}
                                            />
                                        </div>
                                    </div>
                                </div> */}
                            </div>
                        </Paper>
                    </div>
                </div>
            </div>
        );

    }
}

export default MaintenanceMode;