
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as DateUtils from "utils/DateUtils";
import * as UrlUtils from "utils/ApiPathConst";

import {
    Grid, Typography, Button,
    Stack, Box,
    Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import { notifyActionError } from 'utils/CommonFunction';

import { FormattedMessage, useIntl } from "react-intl";

import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import { PRIMARY_OUTLINED_BUTTON_SX } from 'themes/colorConst';

// ==============================|| DASHBOARD - DEFAULT ||============================== //

const Index = () => {
    const [isWarningPopUp, setIsWarningPopUp] = React.useState(false);
    const [warningText, setWarningText] = React.useState("");
    const [resultStr, setResultStr] = React.useState("");
    const [wait, setWait] = React.useState(false);

    const intl = useIntl();


    const BackgroundHead = {
        backgroundImage: `url(${titleBackgroundImg})`,
        width: 'auto',
        height: 'auto',
        backgroundSize: 'contain',
        backgroundRepeat: 'no-repeat',
        backgroundColor: '#0C489E',
        backgroundPosition: 'right'
    }


    const readFile = (event) => {
        let file = event.target.files[0];
        setWait(true);
        if (file) {
            
            if (file.name.toLowerCase().substr(file.name.length - 5).includes(".xlsx")
            ) {
                HttpUtils.postWithFiles({
                    url: UrlUtils.DR_IMPORT,
                    params:null,
                    files: [event.target.files[0]],
                    onSuccess: function (responData) {
                        setWait(false);
                        if(responData?.msg){
                            setResultStr(<>{DateUtils.datetimeStr(new Date())}<br/><span style={{"color": "red"}}>Error</span><br/><span style={{"whiteSpace": "pre-line"}}>{responData?.msg}</span></>)
                        }else if(responData?.success){
                            setResultStr(<>{DateUtils.datetimeStr(new Date())}<br/><span style={{"color": "green"}}>Success</span><br/>Record Count: {responData.recordCount}</>)
                        }
                    },
                    onError: function(){
                        setWait(false);
                        setResultStr(<>{DateUtils.datetimeStr(new Date())}<br/><span style={{"color": "red"}}>Error</span><br/>Action Fail: Please import valid file.</>)
                    }
                });
            } else {
                setWait(false);
                setWarningText("Please upload a valid file (file format: .xlsx)");
                setIsWarningPopUp(true);
                document.getElementById("uploadFileBtn").value = "";
                return;
            }
        }else{
            setWait(false);
        }
        document.getElementById("uploadFileBtn").value = "";
    }
    
    const readOfflineFile = (event) => {
        let file = event.target.files[0];
        setWait(true);
        if (file) {
            
            if (file.name.toLowerCase().substr(file.name.length - 5).includes(".xlsx")
            ) {
                HttpUtils.postWithFiles({
                    url: UrlUtils.OFFLINE_IMPORT,
                    params:null,
                    files: [event.target.files[0]],
                    onSuccess: function (responData) {
                        setWait(false);
                        if(responData?.msg){
                            setResultStr(<>{DateUtils.datetimeStr(new Date())}<br/><span style={{"color": "red"}}>Error</span><br/><span style={{"whiteSpace": "pre-line"}}>{responData?.msg}</span></>)
                        }else if(responData?.success){
                            setResultStr(<>{DateUtils.datetimeStr(new Date())}<br/><span style={{"color": "green"}}>Success</span><br/>Record Count: {responData.recordCount}</>)
                        }
                    },
                    onError: function(){
                        setWait(false);
                        setResultStr(<>{DateUtils.datetimeStr(new Date())}<br/><span style={{"color": "red"}}>Error</span><br/>Action Fail: Please import valid file.</>)
                    }
                });
            } else {
                setWait(false);
                setWarningText("Please upload a valid file (file format: .xlsx)");
                setIsWarningPopUp(true);
                document.getElementById("uploadOfflineFileBtn").value = "";
                return;
            }
        }else{
            setWait(false);
        }
        document.getElementById("uploadOfflineFileBtn").value = "";
    }

    return (
        <Grid container sx={{ minHeight: '87vh', backgroundColor: 'backgroundColor.default' }} direction="column" alignItems="center">
            <Grid item xs={12} md={12} width="100%" >
                <div style={BackgroundHead}>
                    <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                        <Typography ml={15} color='#FFF' variant="h4" sx={{ display: { xs: 'none', sm: 'none', md: 'block' } }}>
                            DR Import
                        </Typography>
                    </Stack>
                </div>
            </Grid>

            <Grid item xs={12} md={12} sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1, }} width="98%">
                <Box xs={12} md={12} sx={{ borderRadius: '10px', backgroundColor: '#fff', p: 4 }}>
                    <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">

                        <Button
                            aria-label={intl.formatMessage({ id: 'uploadFileBtn' })}
                            component="span"
                            variant="outlined"
                            size="large"
                            onClick={()=>{
                                HttpUtils.fileDownload({
                                    url: UrlUtils.DR_EXPORT,
                                    onResponse: () => {},
                                    onError: () => {
                                        notifyActionError(intl.formatMessage({ id: 'downloadFailed' }));
                                    }
                                });
                            }}
                        >Export DR Excel
                        </Button>
                        <Grid item sx={{ pl: 4 }}>
                            <Grid container direction="row" justifyContent="flex-start" alignItems="center">
                                <Grid item xs={12} md={6} lg={6} sx={{ wordBreak: 'break-word' }}>
                                    <input
                                        id="uploadFileBtn"
                                        name="file"
                                        type="file"
                                        accept=".xlsx"
                                        style={{ display: 'none' }}
                                        onChange={(event) => {
                                            readFile(event)
                                        }}
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid item >
                            <Grid container direction="row" justifyContent="flex-start" alignItems="center">
                                <Grid item xs={12} >
                                    <label htmlFor="uploadFileBtn">
                                        <Button
                                            aria-label={intl.formatMessage({ id: 'uploadFileBtn' })}
                                            component="span"
                                            variant="outlined"
                                            size="large"
                                            sx={PRIMARY_OUTLINED_BUTTON_SX}
                                        >Import DR Excel</Button>
                                    </label>
                                </Grid>
                                
                            </Grid>
                        </Grid>
                        <Grid item sx={{ pl: 4 }}>
                            <Grid container direction="row" justifyContent="flex-start" alignItems="center">
                                <Grid item xs={12} md={6} lg={6} sx={{ wordBreak: 'break-word' }}>
                                    <input
                                        id="uploadOfflineFileBtn"
                                        name="file"
                                        type="file"
                                        accept=".xlsx"
                                        style={{ display: 'none' }}
                                        onChange={(event) => {
                                            readOfflineFile(event)
                                        }}
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid item>
                            <Grid container direction="row" justifyContent="flex-end" alignItems="center">
                                <Grid item xs={12} >
                                    <label htmlFor="uploadOfflineFileBtn">
                                        <Button
                                            aria-label={intl.formatMessage({ id: 'uploadFileBtn' })}
                                            component="span"
                                            variant="outlined"
                                            size="large"
                                            sx={PRIMARY_OUTLINED_BUTTON_SX}
                                        >Import Offline Mode Application</Button>
                                    </label>
                                </Grid>
                                
                            </Grid>
                        </Grid>

                    </Stack>
                </Box>
            </Grid>

            <Grid item xs={12} md={12} sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1, }} width="98%" >
                <Box xs={12} md={12} sx={{ borderRadius: '10px', backgroundColor: '#fff', p: 4 }}>

                    <Typography variant="h4">Result:</Typography>
                    <Box xs={12} md={12} sx={{ pl: 4 }}>
                        {resultStr}
                    </Box>


                </Box>
            </Grid>

            <div>
                <Dialog
                    open={isWarningPopUp}
                    onClose={() => setIsWarningPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle>
                        Action Fail
                    </DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h5" style={{ padding: '16px' }}>{warningText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button
                            aria-label={intl.formatMessage({ id: 'close' })}
                            onClick={() => { setIsWarningPopUp(false); }}
                        >
                            <FormattedMessage id="close" />
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={wait}
                    onClose={() => setWait(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>Please wait ...</Typography>
                    </DialogContent>
                </Dialog>
            </div>
        </Grid>
    );
};

export default Index;