// material-ui
import {
    Grid,
    Typography,
    Stack,
    Button,
    CircularProgress,
    Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import MainCard from "components/MainCard";
import {GEN_GFMIS_XML} from "utils/ApiPathConst";
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as DateUtils from "utils/DateUtils";

import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";

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')));
const TransactionTable = Loadable(React.lazy(() => import('./TransactionDataGrid')));
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 [isTxLoading, setIsTxLoading] = React.useState(false);
    const [autoPreviewPending, setAutoPreviewPending] = React.useState(false);

    const [searchCriteria, setSearchCriteria] = React.useState({
        dateTo: DateUtils.dateValue(new Date()),
        dateFrom: DateUtils.dateValue(new Date().setDate(new Date().getDate()-14)),
    });
    const [previewSearchCriteria, setPreviewSearchCriteria] = React.useState({
        dateTo: DateUtils.dateValue(new Date()),
        dateFrom: DateUtils.dateValue(new Date().setDate(new Date().getDate()-14)),
    });
    const [onReady, setOnReady] = React.useState(false);
    const [onGridReady, setGridOnReady] = React.useState(false);
    const [isPreviewLoading, setIsPreviewLoading] = React.useState(false);
   
    const [isPopUp, setIsPopUp] = React.useState(false);
    const [isXmlDialogSubmitting, setIsXmlDialogSubmitting] = React.useState(false);
    const xmlDownloadInFlightRef = React.useRef(false);
    const [downloadInput, setDownloadInput] = React.useState();
    const [selectedIds, setSelectedIds] = React.useState([]);

    const [inputDate, setInputDate] = React.useState(searchCriteria.dateTo);
    const [inputDateValue, setInputDateValue] = React.useState("dd / mm / yyyy");
    const [previewToken, setPreviewToken] = React.useState(0);

    React.useEffect(() => {
        setInputDateValue(inputDate);
    }, [inputDate]);

    React.useEffect(() => {
        if (!isPopUp) {
            xmlDownloadInFlightRef.current = false;
            setIsXmlDialogSubmitting(false);
        }
    }, [isPopUp]);

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

    React.useEffect(() => {
        if (!autoPreviewPending) return;

        // wait for tx grid load complete, and for auto-selection to happen
        if (isTxLoading) return;
        if (!selectedIds || selectedIds.length === 0) return;

        // trigger preview exactly once
        const withToken = { ...searchCriteria, __ts: Date.now() };
        setPreviewSearchCriteria(withToken);
        setPreviewToken(t => t + 1);

        setAutoPreviewPending(false);
    }, [autoPreviewPending, isTxLoading, selectedIds, searchCriteria]);

    React.useEffect(() => {
        if (selectedIds.length === 0) {
            setPreviewSearchCriteria({});
            setPreviewToken(t => t + 1); // forces preview grid remount -> clears rows
        }
    }, [selectedIds]);


    function downloadXML() {
        if (xmlDownloadInFlightRef.current) return;
        xmlDownloadInFlightRef.current = true;
        console.log(selectedIds.join(','));
        setIsXmlDialogSubmitting(true);
        let sentDateFrom = "";

        if (inputDateValue != "dd / mm / yyyy") {
            sentDateFrom = DateUtils.dateValue(inputDateValue);
        }
        HttpUtils.get({
            url: GEN_GFMIS_XML + "/today",
            params: {
                dateTo: downloadInput.dateTo,
                dateFrom: downloadInput.dateFrom,
                inputDate: sentDateFrom,
                paymentId: selectedIds.join(',')
            },
            onSuccess: (responseData) => {
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(responseData, 'application/xml');
                const dcbHeader = xmlDoc.querySelector("DCBHeader");

                const receiptElements = Array.from(dcbHeader.querySelectorAll("Receipt"));
                const allocationElements = Array.from(dcbHeader.querySelectorAll("Allocation"));
                const paymentMethodElements = Array.from(dcbHeader.querySelectorAll("PaymentMethod"));

                dcbHeader.innerHTML = "";

                receiptElements.forEach((receiptElement) => {
                    dcbHeader.appendChild(receiptElement);
                });
                allocationElements.forEach((allocationElement) => {
                    dcbHeader.appendChild(allocationElement);
                });
                paymentMethodElements.forEach((paymentMethodElement) => {
                    dcbHeader.appendChild(paymentMethodElement);
                });

                const updatedXmlString = new XMLSerializer().serializeToString(xmlDoc);
                const filename = xmlDoc.querySelector('FileHeader').getAttribute('H_Filename');
                const blob = new Blob([updatedXmlString], { type: 'application/xml' });
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = filename + '.xml';

                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                setIsPopUp(false);
            },
            onFinally: () => {
                xmlDownloadInFlightRef.current = false;
                setIsXmlDialogSubmitting(false);
            }
        });
    }


    function applySearch(input) {
        setAutoPreviewPending(true);   // NEW: ask for auto-preview after grid loads
        setGridOnReady(true);
        setSelectedIds([]);
        setPreviewSearchCriteria({});
        setSearchCriteria(input);
        setInputDate(input.dateFrom);
    }


    function previewSearch() {
        if (selectedIds.length === 0) return;

        setIsPopUp(false);
        setIsPreviewLoading(true);

        const withToken = { ...searchCriteria, __ts: Date.now() };
        setPreviewSearchCriteria(withToken);

        setPreviewToken(t => t + 1);
    }


    function onPreviewGridOnReady(isLoading) {
        // FiDataGrid calls this with true/false
        setIsPreviewLoading(isLoading);
    }


    function applyGridOnReady(isLoading) {
        setGridOnReady(isLoading);   // keep existing behavior for disabling Search
        setIsTxLoading(isLoading);   // NEW: remember tx grid loading
    }

    function generateXML(input) {
        setDownloadInput(input);
        setIsPopUp(true)
    }

    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" }}>
                            GFMIS Generate XML
                            </Typography>
                        </Stack>
                    </div>
                </Grid>
                {/*row 1*/}
                <Grid item xs={12} md={12} lg={12} sx={{mb:-1}}>
                    <SearchForm 
                        applySearch={applySearch}
                        generateXML={generateXML}
                        searchCriteria={searchCriteria}
                        onGridReady={onGridReady}
                        selectedIds={selectedIds}
                    />

                </Grid>
                {/*row 2*/}
                <Grid item xs={12} md={12} lg={12}>
                    <MainCard elevation={0}
                            border={false}
                            content={false}
                            sx={{width: "-webkit-fill-available"}}
                    >
                        <TransactionTable
                            searchCriteria={searchCriteria}
                            applyGridOnReady={applyGridOnReady}
                            applySearch={applySearch}
                            selectedIds={selectedIds}
                            onSelectionChange={setSelectedIds}
                        />
                    </MainCard>
                </Grid>
                <Grid item xs={12} md={12} lg={12} sx={{ml:2}}>
                    <Button
                        variant="contained"
                        onClick={previewSearch}
                        disabled={isPreviewLoading || selectedIds.length === 0}
                    >
                        Preview
                    </Button>

                </Grid>
                <Grid item xs={12} md={12} lg={12}>
                    <MainCard elevation={0}
                            border={false}
                            content={false}
                            sx={{width: "-webkit-fill-available"}}
                    >
                        <EventTable
                            previewSearchCriteria={previewSearchCriteria}
                            onPreviewGridOnReady={onPreviewGridOnReady}
                            selectedIds={selectedIds}
                            previewToken={previewToken}
                        />

                    </MainCard>
                </Grid>
                <Dialog
                    open={isPopUp}
                    onClose={() => {
                        if (isXmlDialogSubmitting) return;
                        setIsPopUp(false);
                    }}
                    disableEscapeKeyDown={isXmlDialogSubmitting}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle> Bank Statement Collection Date </DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <LocalizationProvider dateAdapter={AdapterDayjs}>
                            <DemoItem  components={['DatePicker']}>
                                <DatePicker
                                    id="dateFrom"
                                    // onError={(newError) => setReceiptFromError(newError)}
                                    slotProps={{
                                        field: { readOnly: true, },
                                        // textField: {
                                        //     helperText: receiptFromErrorMessage,
                                        // },
                                    }}
                                    format="DD/MM/YYYY"
                                    // label="Credit Date"
                                    value={inputDate === null ? null : dayjs(inputDate)}
                                    minDate={searchCriteria.dateFrom === null ? null : dayjs(searchCriteria.dateFrom)}
                                    onChange={(newValue) => {
                                        // console.log(newValue)
                                        if(newValue!=null){
                                            setInputDate(newValue);
                                        }
                                    }}
                                />
                            </DemoItem >
                        </LocalizationProvider>
                    </DialogContent>
                    <DialogActions>
                        <Button
                            onClick={() => {
                                if (isXmlDialogSubmitting) return;
                                setIsPopUp(false);
                            }}
                            disabled={isXmlDialogSubmitting}
                        >
                            <Typography variant="h5">Cancel</Typography>
                        </Button>
                        <Button
                            onClick={() => downloadXML()}
                            disabled={isXmlDialogSubmitting}
                            startIcon={isXmlDialogSubmitting ? <CircularProgress color="inherit" size={20} /> : null}
                        >
                            <Typography variant="h5">Confirm</Typography>
                        </Button>
                    </DialogActions>
                </Dialog>
            </Grid>
    );
};

export default Index;
