// material-ui
import * as React from 'react';
import {
    //Link,
    Button,
    Grid,
    Typography,
    Stack,
    Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import { GET_PUBLIC_NOTICE_LIST, SET_PUBLIC_NOTICE_STATUS_PUBLISH_BULK } from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
import * as DateUtils from "utils/DateUtils";
import * as FormatUtils from "utils/FormatUtils";
import * as StatusUtils from "utils/statusUtils/PublicNoteStatusUtils";
import { useNavigate } from "react-router-dom";
import { FiDataGrid } from "components/FiDataGrid";
import { notifyActionSuccess, clickableLink } from 'utils/CommonFunction';
import { FormattedMessage, useIntl } from "react-intl";
import * as utils from "auth/utils"
import { isGrantedAny } from "auth/utils";
// ==============================|| EVENT TABLE ||============================== //

export default function SearchPublicNoticeTable({ searchCriteria, applyGridOnReady, applySearch }) {

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

    const [selectedRowItems, setSelectedRowItems] = React.useState([]);
    const [isConfirmPopUp, setIsConfirmPopUp] = React.useState(false);
    const [isWarningPopUp, setIsWarningPopUp] = React.useState(false);

    const [reload, setReload] = React.useState(new Date());

    const intl = useIntl();

    const [_searchCriteria, set_searchCriteria] = React.useState(searchCriteria);
    React.useEffect(() => {
        set_searchCriteria(searchCriteria);
    }, [searchCriteria]);


    function genIssueNo(params) {
        const issueNo = params.row.issueYear + " Vol. " + FormatUtils.zeroPad(params.row.issueVolume, 3) + ", No. " + FormatUtils.zeroPad(params.row.issueNo, 2) + ", " + DateUtils.dateFormat(params.row.issueDate, "D MMM YYYY (ddd)")
        return issueNo
    }

    function genGroupNo(params) {
        let groupNo = params.row.groupNo
        if (groupNo != null) {
            groupNo = <><br /><div>{groupNo}</div></>
        }
        return groupNo
    }

    const renderHeaderWithAria = (params) => (
        <span aria-label={params.colDef.headerName}>{params.colDef.headerName}</span>
    );

    const columns = [
        {
            field: 'actions',
            headerName: 'Application No.',
            sortable: false,
            width: 150,
            cellClassName: 'actions',
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                return clickableLink('/application/' + params.id, params.row.appNo);
            },
        },
        {
            id: 'mode',
            field: 'mode',
            headerName: 'Mode',
            sortable: false,
            width: 100,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                return StatusUtils.getModeEng(params);
            },
        },
        {
            id: 'status',
            field: 'status',
            headerName: 'Status',
            sortable: false,
            width: 240,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                return StatusUtils.getStatusEng(params);
            },
        },
        {
            id: 'withProof',
            field: 'withProof',
            headerName: 'With Proof',
            sortable: false,
            width: 120,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                return params.row.proofId != null ? "Yes" : "";
            },
        },
        {
            id: 'created',
            field: 'created',
            headerName: 'Submit Date',
            sortable: false,
            flex: 1,
            minWidth: 200,
            renderHeader: renderHeaderWithAria,
            valueGetter: (params) => {
                return DateUtils.datetimeStr(params?.value);
            }
        },
        {
            id: 'contactPerson',
            field: 'contactPerson',
            headerName: 'Client / Payment Means',
            sortable: false,
            minWidth: 250,
            flex: 2,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                let company = params.row.enCompanyName != null ? params.row.enCompanyName : params.row.chCompanyName;
                company = company != null ? company : "";
                if (company == "GLD"){
                    company = company + ": " + params.row.custName
                }
                let paymentMethod = params.row.paymentMethod!=null?intl.formatMessage({ id: utils.getPaymentMethod(params.row.paymentMethod)}):""
                return (<>
                    {params?.value}<br />{company} <br/>{paymentMethod}
                </>);
            }
        },
        {
            id: 'issueNoAndCode',
            field: 'issueNoAndCode',
            headerName: 'Gazette Issue No. / Gazette Code',
            sortable: false,
            flex: 1.5,
            minWidth: 350,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => (
                <div>
                    {genIssueNo(params)}
                    {genGroupNo(params)}
                </div>

            )
        },
    ];

    function handleRowDoubleClick(params) {
        // handleEditClick(params)
        navigate('/application/' + params.id);
    }

    const doPublish = () => {
        setIsConfirmPopUp(false);
        let appIdList = [];
        const datas = rows?.filter((row) =>
            selectedRowItems.includes(row.id)
        );
        // console.log(datas)
        for (var i = 0; i < datas?.length; i++) {
            appIdList.push(datas[i].id);
        }
        if (appIdList.length < 1) {
            setIsWarningPopUp(true);
        } else {
            HttpUtils.post({
                url: SET_PUBLIC_NOTICE_STATUS_PUBLISH_BULK,
                params: {
                    ids: appIdList
                },
                onSuccess: () => {
                    setReload(new Date());
                    notifyActionSuccess("Action Success!")
                }
            });
        }
    }

    return (<>

        <div style={{ width: '100%' }}>
            {isGrantedAny(["MAINTAIN_APPLICATION"]) ?
                <Grid container direction="row" justifyContent="flex-start" alignItems="center" sx={{ p: 1 }} >
                    <Button
                        variant="contained"
                        onClick={() => setIsConfirmPopUp(true)}
                    >
                        Published
                    </Button>
                </Grid>
                :null
            }

            <FiDataGrid
                checkboxSelection
                disableRowSelectionOnClick
                onRowSelectionModelChange={(newSelection) => {
                    setSelectedRowItems(newSelection);
                }}
                isRowSelectable={(params) => {
                    return ((params.row.creditor === true && params.row.status == "confirmed") ||
                        (params.row.creditor === false && params.row.status == "paid"))
                }}
                columns={columns}
                customPageSize={10}
                getRowHeight={() => 'auto'}
                onRowDoubleClick={handleRowDoubleClick}
                applyGridOnReady = {applyGridOnReady}
                applySearch = {applySearch}
                doLoad={React.useMemo(() => ({
                    url: GET_PUBLIC_NOTICE_LIST,
                    params: _searchCriteria,
                    applyGridOnReady: applyGridOnReady,
                    callback: function (responseData) {
                        setRows(responseData?.records);
                        // applyGridOnReady(false)
                    }
                }), [_searchCriteria, reload])}
            />
        </div>
        <div>
            <Dialog
                open={isConfirmPopUp}
                onClose={() => setIsConfirmPopUp(false)}
                PaperProps={{
                    sx: {
                        minWidth: '40vw',
                        maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '30vw' },
                        maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '50vh' }
                    }
                }}
            >
                <DialogTitle>
                    <Typography variant="h3" >
                        <FormattedMessage id="confirm" />
                    </Typography>
                </DialogTitle>
                <DialogContent style={{ display: 'flex', }}>
                    <Stack direction="column" justifyContent="space-between">
                        <Typography variant="h4" style={{ padding: '16px' }}>Please Confirm to mark selected application as Published.</Typography>
                    </Stack>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setIsConfirmPopUp(false)} aria-label={intl.formatMessage({ id: 'close' })}>
                        <Typography variant="h5">
                            <FormattedMessage id="close" />
                        </Typography></Button>

                    <Button onClick={() => doPublish()} aria-label={intl.formatMessage({ id: 'confirm' })}>
                        <Typography variant="h5">
                            <FormattedMessage id="confirm" />
                        </Typography></Button>
                </DialogActions>
            </Dialog>
        </div>
        <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><Typography variant="h3">Warning</Typography></DialogTitle>
                <DialogContent style={{ display: 'flex', }}>
                    <Typography variant="h4" style={{ padding: '16px' }}>{intl.formatMessage({ id: "MSG.plzSelectApp" })}</Typography>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setIsWarningPopUp(false)}><Typography variant="h5">OK</Typography></Button>
                </DialogActions>
            </Dialog>
        </div>
    </>

    );
}
