// material-ui
import { useState, useEffect, useMemo } from 'react';
import {
    Grid,
    Typography,
    Button,
    Box,
    Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import DownloadIcon from '@mui/icons-material/Download';
import * as DateUtils from "utils/DateUtils";
import * as FormatUtils from "utils/FormatUtils";
import * as StatusUtils from "utils/statusUtils/DnStatus";
import { useNavigate } from "react-router-dom";
import { FiDataGrid } from "components/FiDataGrid";
import { notifyActionError } from 'utils/CommonFunction';
import {
    DEMAND_NOTE_EXPORT,
    DEMAND_NOTE_SEND,
    DEMAND_NOTE_ATTACH,
    DEMAND_NOTE_MARK_PAID,
    DEMAND_NOTE_LIST_ALL,
    DEMAND_NOTE_REVOKE_PAID
} from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
import { PNSPS_BUTTON_THEME } from "themes/buttonConst";
import { ThemeProvider } from "@emotion/react";
import { isGrantedAny } from "auth/utils";
import { useIntl } from "react-intl";
// ==============================|| EVENT TABLE ||============================== //

export default function SearchDemandNote({ applySearch, searchCriteria, applyGridOnReady }) {
    const intl = useIntl();
    const [isConfirmPopUp, setConfirmPopUp] = useState(false);
    const [isRevokePopUp, setRevokePopUp] = useState(false);
    const [isSendPopUp, setSendPopUp] = useState(false);
    const [isErrorPopUp, setIsErrorPopUp] = useState(false);
    const [selectonWarning, setSelectonWarning] = useState(false);
    const [wait, setWait] = useState(false);
    const [reload, setReload] = useState(new Date());
    const [rows, setRows] = useState([]);
    const [_searchCriteria, set_searchCriteria] = useState({});
    const [selectedRowItems, setSelectedRowItems] = useState([]);
    const navigate = useNavigate()
    const [onDownload, setOnDownload] = useState(false);

    useEffect(() => {
        set_searchCriteria(searchCriteria);
    }, [searchCriteria]);


    const handleDnClick = (params) => () => {
        navigate('/paymentPage/demandNote/details/' + params.id);
    };

    const findReadyToSend = () => {
        const temp = {
            readySend: true
        };
        applySearch(temp);
    }

    const exportXml = () => {
        let idList = [];
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        if (datas?.length < 1) {
            setSelectonWarning(true);
            return;
        } else if (datas?.length >= 100) {
            setIsErrorPopUp(true);
            return;
        }
        for (var i = 0; i < datas?.length; i++) {
            idList.push(datas[i].id);
        }
        HttpUtils.fileDownload({
            method: 'post',
            url: DEMAND_NOTE_EXPORT,
            params: {
                dnIdList: idList
            },
            onResponse: function () {},
            onError: function () {
                notifyActionError(intl.formatMessage({ id: 'downloadFailed' }));
            }
        });
    }

    const onDownloadClick = (params) => () => {
        setOnDownload(true)
        HttpUtils.fileDownload({
            fileId: params.row.fileId,
            skey: params.row.skey,
            filename: params.row.filename,
            onResponse: () => {
                setOnDownload(false);
            },
            onError: () => {
                setOnDownload(false);
                notifyActionError(intl.formatMessage({ id: 'downloadFailed' }));
            }
        });
    };

    const onSendClick = () => {
        setSendPopUp(false)
        let idList = [];
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        if (datas?.length < 1) {
            setSelectonWarning(true);
            return;
        }
        for (var i = 0; i < datas?.length; i++) {
            idList.push(datas[i].id);
        }
        HttpUtils.post({
            url: DEMAND_NOTE_SEND,
            params: {
                dnIdList: idList
            },
            onSuccess: () => {
                setReload(new Date());
            }
        });

    }

    const doUploadFile = (event) => {
        setWait(true);
        let dnMap = {};
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        for (var i = 0; i < datas?.length; i++) {
            let dnNo = datas[i].dnNo.replaceAll("-", "");
            dnMap[dnNo] = datas[i].id
        }
        let file = event.target.files[0];
        HttpUtils.postWithFiles({
            url: DEMAND_NOTE_ATTACH,
            params: {
                dnMap: dnMap
            },
            files: [file],
            onSuccess() {
                setReload(new Date());
            },
        });
        document.getElementById("uploadFileBtn").value = "";
    }

    const revokePaid = () => {
        setRevokePopUp(false);
        let idList = [];
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        if (datas?.length < 1) {
            setSelectonWarning(true);
            return;
        }
        for (var i = 0; i < datas?.length; i++) {
            idList.push(datas[i].id);
        }
        HttpUtils.post({
            url: DEMAND_NOTE_REVOKE_PAID,
            params: {
                dnIdList: idList
            },
            onSuccess: () => {
                setReload(new Date());
            }
        });
    }

    const markPaid = () => {
        setConfirmPopUp(false);
        let idList = [];
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        if (datas?.length < 1) {
            setSelectonWarning(true);
            return;
        }
        for (var i = 0; i < datas?.length; i++) {
            idList.push(datas[i].id);
        }
        HttpUtils.post({
            url: DEMAND_NOTE_MARK_PAID,
            params: {
                dnIdList: idList
            },
            onSuccess: () => {
                setReload(new Date());
            }
        });
    }

    function handleRowDoubleClick(params) {
        handleDnClick(params);
    }

    const columns = [
        {
            field: 'appNo',
            headerName: 'Application No.',
            width: 150,
        },
        {
            id: 'contactPerson',
            field: 'contactPerson',
            headerName: 'Organisation',
            minWidth: 300,
            flex: 1,
            renderCell: (params) => {
                let company = params.row.enCompanyName != null ? params.row.enCompanyName : params.row.chCompanyName;
                company = company != null ? company : "";

                /*
                let phone = JSON.parse(params.row.contactTelNo);
                let faxNo = JSON.parse(params.row.contactFaxNo);

                let contact = "";
                if (phone) {
                    contact = "Phone No.: " + phone?.countryCode + " " + phone?.phoneNumber
                }

                if (faxNo && faxNo?.faxNumber) {
                    if (contact != "")
                        contact = contact + ", "
                    contact = contact + "Fax No.:" + faxNo?.countryCode + " " + faxNo?.faxNumber
                }
                */

                return (<>
                    {params?.value}<br />{company}
                </>);
            }
        },
        {
            field: 'cm',
            headerName: 'Length',
            width: 120,
            renderCell: (params) => {
                return (<>
                    {params?.value + "cm"}<br />
                    {params.row.column}
                </>);
            }
        },
        {
            field: 'amount',
            headerName: 'Amount ($)',
            width: 120,
            align: 'right',
            valueGetter: (params) => {
                return FormatUtils.currencyFormat(params?.value);
            }
        },
        {
            field: 'dnNo',
            headerName: 'DN No.',
            width: 250,
            renderCell: (params) => {
                return <Button sx={{ fontSize: '8px' }} onClick={handleDnClick(params)}><u>{params.row.dnNo}</u></Button>;
            },
        },
        {
            id: 'dueDate',
            field: 'dueDate',
            headerName: 'Issue / Due / Sent Date',
            width: 300,
            renderCell: (params) => {
                return (<table>
                    <tbody>
                        <tr><td>Issue:</td><td>{DateUtils.dateStr(params?.row.issueDate)}</td></tr>
                        <tr><td>Due:</td><td>{params?.value ? DateUtils.dateStr(params?.value) : "--"}</td></tr>
                        <tr><td>Sent:</td><td>{params.row.sentDate ? DateUtils.datetimeStr(params.row.sentDate) +" - "+  params.row.sentBy :  "To be sent"}</td></tr>
                    </tbody>
                </table>);
            }
        },
        {
            field: 'filename',
            //headerName: 'DN File',
            renderHeader: () => (
                <><DownloadIcon />DN File</>
            ),
            width: 280,
            renderCell: (params) => {
                return <Button disabled={onDownload} onClick={onDownloadClick(params)}><u>{params.row.filename}</u></Button>;
            },
        },
        {
            field: 'status',
            headerName: 'Status',
            width: 175,
            renderCell: (params) => {
                return StatusUtils.getStatus_Eng(params)
            },
        },
    ];

    return (
        <div style={{ width: '100%' }}>
            {isGrantedAny(["MAINTAIN_DEMANDNOTE"]) ?
                <Grid container maxWidth justifyContent="flex-start">
                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                        <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
                            <input
                                id="uploadFileBtn"
                                name="file"
                                type="file"
                                accept=".pdf"
                                style={{ display: 'none' }}
                                onChange={(event) => {
                                    const datas = rows?.filter((row) =>
                                        selectedRowItems.includes(row.id)
                                    );
                                    if (datas.length == 0) {
                                        setSelectonWarning(true);
                                        document.getElementById("uploadFileBtn").value = "";
                                        return;
                                    }
                                    doUploadFile(event)
                                }}
                            />
                            <label htmlFor="uploadFileBtn">
                                <Button
                                    component="span"
                                    variant="contained"
                                >
                                    Attach DN
                                </Button>
                            </label>
                        </Grid>

                        <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
                            <Button
                                variant="contained"
                                onClick={findReadyToSend}
                            >
                                Ready Send
                            </Button>
                        </Grid>
                        <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
                            <Button
                                variant="contained"
                                onClick={() => setSendPopUp(true)}
                            >
                                Send DN
                            </Button>
                        </Grid>

                        <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
                            <Button
                                variant="contained"
                                onClick={() => exportXml()}>
                                Export GDNS
                            </Button>
                        </Grid>


                        <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
                            <Button
                                variant="contained"
                                onClick={() => setConfirmPopUp(true)}
                            >
                                Mark as Paid
                            </Button>
                        </Grid>

                        <Grid item sx={{ ml: 3, mr: 3, mb: 3, mt: 3 }}>
                            <Button
                                variant="contained"
                                onClick={() => setRevokePopUp(true)}
                            >
                                Revoke payment
                            </Button>
                        </Grid>

                    </ThemeProvider>
                </Grid>
                : <></>
            }
            <Box sx={{ backgroundColor: "#fff", ml: 2 }} width="98%">
                <FiDataGrid
                    checkboxSelection={isGrantedAny(["MAINTAIN_DEMANDNOTE"])}
                    disableRowSelectionOnClick
                    onRowSelectionModelChange={(newSelection) => {
                        setSelectedRowItems(newSelection);
                    }}
                    columns={columns}
                    customPageSize={100}
                    getRowHeight={() => 'auto'}
                    onRowDoubleClick={handleRowDoubleClick}
                    applyGridOnReady={applyGridOnReady}
                    applySearch={applySearch}
                    doLoad={useMemo(() => ({
                        url: DEMAND_NOTE_LIST_ALL,
                        params: _searchCriteria,
                        callback: function (responseData) {
                            setRows(responseData?.records);
                        }
                    }), [_searchCriteria, reload])}
                />
            </Box>
            <div>
                <Dialog
                    open={isErrorPopUp}
                    onClose={() => setIsErrorPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Action Fail</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>Number of DN record must less than 100.<br />Please edit search form.</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setIsErrorPopUp(false)}><Typography variant="h5">OK</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={selectonWarning}
                    onClose={() => setSelectonWarning(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Warning</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>Please Select DN.</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setSelectonWarning(false)}><Typography variant="h5">OK</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={isConfirmPopUp}
                    onClose={() => setConfirmPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Confirm</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>Are you sure to mark DN paid?</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setConfirmPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                        <Button onClick={() => markPaid()}><Typography variant="h5">Confirm</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={isRevokePopUp}
                    onClose={() => setRevokePopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Confirm</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>Are you sure to revoke DN as To Be Paid?</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setRevokePopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                        <Button onClick={() => revokePaid()}><Typography variant="h5">Confirm</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={isSendPopUp}
                    onClose={() => setSendPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Confirm</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>Are you sure to send DN?</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setSendPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                        <Button onClick={() => onSendClick()}><Typography variant="h5">Confirm</Typography></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>
        </div>
    );
}
