// material-ui
import {
    Grid,
    Typography,
    Stack
} from '@mui/material';
// import MainCard from "components/MainCard";
import * as UrlUtils from "utils/ApiPathConst";
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
// import * as DateUtils from "utils/DateUtils";
// import axios from "axios";

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
const SearchForm = Loadable(React.lazy(() => import('./SearchForm')));
// const EventTable = Loadable(React.lazy(() => import('./DataGrid')));
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'

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

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

const Index = () => {

    // const [record,setRecord] = React.useState([]);
    const [searchCriteria, setSearchCriteria] = React.useState({
        // dateTo: DateUtils.dateValue(new Date()),
        // dateFrom: DateUtils.dateValue(new Date().setDate(new Date().getDate()-14)),
    });
    const [onReady] = React.useState(true);
    // const [onDownload, setOnDownload] = React.useState(false);
    const [onLoad, setonLoad] = React.useState(false);

    // React.useEffect(() => {
    //     setOnReady(true);
    // }, [record]);

    React.useEffect(() => {
        if (Object.keys(searchCriteria).length > 0){
            // console.log(searchCriteria)
            loadGrid();
        }
    }, [searchCriteria]);

    function loadGrid(){
        setonLoad(true)
        HttpUtils.get({
            url: UrlUtils.VIEW_RECON_REPORT,
            params: searchCriteria,
            onSuccess: function(responseData){
                // console.log(responseData)
                if(responseData.status != 200){
                    alert(responseData.content)
                    setonLoad(false)
                } else {
                    var myWindow = window.open();
                    myWindow.document.write(responseData.content);
                    setonLoad(false)
                }
            },
            onError:()=>{
                setonLoad(false)

            }
        });
    }

    function downloadXML(input) {
        // console.log(input)
        const hasCollRange = input.CollDateFrom!="" && input.CollDateTo!="";
        const hasTxnRange = input.TxnDateFrom!="" && input.TxnDateTo!="";
        const hasSysTxnRange = input.SysTxnDateFrom!="" && input.SysTxnDateTo!="";

        let countRanges= 0;
        if(hasCollRange) countRanges+=1;
        if(hasTxnRange) countRanges+=1;
        if(hasSysTxnRange) countRanges+=1;

        if(countRanges>1){
            alert("Only one date range is allowed Trans/Coll dates")
            // return "<div>Only one date range is allowed Trans/Coll dates</div>";
        }else if(countRanges == 0){
            alert("Must have a date range")
            // return "<div>must have a date range</div>";
        }else{
            setonLoad(true)
            HttpUtils.fileDownload({
                url: UrlUtils.GEN_RECON_REPORT,
                params:input,
                onResponse:(response)=>{
                    console.log(response)
                    setonLoad(false)
                },
                onError:()=>{
                    setonLoad(false)
                }
              });
        }
        // open(UrlUtils.GEN_GFMIS_XML + "/today?online=true") 
      }


    function applySearch(input) {
        setSearchCriteria(input);
    }

    function generateReport(input) {
        downloadXML(input);
    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <Grid container sx={{minHeight: '87vh', backgroundColor: 'backgroundColor.default'}} direction="column">
                <Grid item xs={12}>
                    <div style={BackgroundHead}>
                        <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                            <Typography ml={15} color='#FFF' variant="h4" sx={{ "textShadow": "0px 0px 25px #0c489e" }}>
                            Recon Report
                            </Typography>
                        </Stack>
                    </div>
                </Grid>
                {/*row 1*/}
                <Grid item xs={12} md={12} lg={12} sx={{mb:-1}}>
                    <SearchForm 
                    applySearch={applySearch}
                    generateReport={generateReport}
                    searchCriteria={searchCriteria}
                    onLoad={onLoad}
                    />
                </Grid>
                {/*row 2*/}
            </Grid>
    );
};

export default Index;
