// material-ui
import * as React 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 * as PublicNoteStatusUtils from "utils/statusUtils/PublicNoteStatusUtils";
import { useNavigate } from "react-router-dom";
import { FiDataGrid } from "components/FiDataGrid";
import { notifyDownloadSuccess } from 'utils/CommonFunction';

import * as UrlUtils from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
// ==============================|| EVENT TABLE ||============================== //

export default function SearchDemandNote({ recordList, reloadFun, applySearch }) {

    const [isConfirmPopUp, setConfirmPopUp] = React.useState(false);
    const [isSendPopUp, setSendPopUp] = React.useState(false);
    const [isErrorPopUp, setIsErrorPopUp] = React.useState(false);
    const [selectonWarning, setSelectonWarning] = React.useState(false);
    const [wait, setWait] = React.useState(false);

    const [rows, setRows] = React.useState(recordList);
    const [selectedRowItems, setSelectedRowItems] = React.useState([]);
    const navigate = useNavigate()

    React.useEffect(() => {
        setRows(recordList);
    }, [recordList]);

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

    const findReadyToSend=()=>{
        const temp = {
            status: 'pending',
        };
        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: UrlUtils.DEMAND_NOTE_EXPORT,
            params: {
                dnIdList: idList
            },
            onSuccess: function () {
                notifyDownloadSuccess();
            }
        });
    }

    const onDownloadClick = (params) => () => {
        HttpUtils.fileDownload({
            fileId: params.row.fileId,
            skey: params.row.skey,
            filename: params.row.filename,
        });
    };

    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: UrlUtils.DEMAND_NOTE_SEND,
            params: {
                dnIdList: idList
            },
            onSuccess: () => {
                if (reloadFun) reloadFun();
            }
        });

    }

    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: UrlUtils.DEMAND_NOTE_ATTACH,
            params: {
                dnMap: dnMap
            },
            files: [file],
            onSuccess() {
                setWait(false);
                if (reloadFun) reloadFun();
            },
        });
        document.getElementById("uploadFileBtn").value = "";
    }

    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: UrlUtils.DEMAND_NOTE_MARK_PAID,
            params: {
                dnIdList: idList
            },
            onSuccess: () => {
                if (reloadFun) reloadFun();
            }
        });
    }

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

    const columns = [
        {
            field: 'appNo',
            headerName: 'App No.',
            width: 120,
        },
        {
            id: 'contactPerson',
            field: 'contactPerson',
            headerName: 'Client',
            width: 300,
            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(cm)',
            width: 100,
            renderCell: (params) => {
                return (<>
                    {params?.value + "cm"}<br />
                    {params.row.column}
                </>);
            }
        },
        {
            field: 'amount',
            headerName: 'Amount($)',
            width: 100,
            valueGetter: (params) => {
                return FormatUtils.currencyFormat(params?.value);
            }
        },
        {
            field: 'dnNo',
            headerName: 'DN No.',
            width: 200,
            renderCell: (params) => {
                return <Button onClick={handleDnClick(params)}><u>{params.row.dnNo}</u></Button>;
            },
        },
        {
            id: 'issueDate',
            field: 'issueDate',
            headerName: 'DN Issue/Due Date',
            width: 175,
            valueGetter: (params) => {
                return DateUtils.dateStr(params?.value);
            }
        },
        {
            field: 'sentDate',
            headerName: 'DN Sent Date',
            width: 175,
            valueGetter: (params) => {
                return params?.value ? DateUtils.datetimeStr(params?.value) + " - " + params.row.sentBy : "";
            }
        },
        {
            field: 'filename',
            //headerName: 'DN File',
            renderHeader: () => (
                <><DownloadIcon />DN File</>
            ),
            width: 250,
            renderCell: (params) => {
                return <Button onClick={onDownloadClick(params)}><u>{params.row.filename}</u></Button>;
            },
        },
        {
            field: 'appStatus',
            headerName: 'App Status',
            width: 175,
            renderCell: (params) => {
                return [PublicNoteStatusUtils.getStatusByTextEng(params?.value, true)]
            },
        },
        {
            field: 'status',
            headerName: 'Status',
            width: 175,
            renderCell: (params) => {
                return [StatusUtils.getStatus_Eng(params)]
            },
        },
    ];

    return (
        <div style={{ width: '100%' }}>
            <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>
                </ThemeProvider>
            </Grid>
            <Box sx={{ backgroundColor: "#fff", ml: 2 }} width="98%">
                <FiDataGrid
                    checkboxSelection
                    disableRowSelectionOnClick
                    onRowSelectionModelChange={(newSelection) => {
                        setSelectedRowItems(newSelection);
                    }}
                    rows={rows}
                    columns={columns}
                    customPageSize={100}
                    getRowHeight={() => 'auto'}
                    onRowDoubleClick={handleRowDoubleClick}
                />
            </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={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' }}>Calculating, please wait ...</Typography>
                    </DialogContent>
                </Dialog>
            </div>
        </div>
    );
}
