// material-ui
import * as React from 'react';
import {
    //Link,
    Button,
    Grid,
    Typography,
    Stack,
    Dialog, DialogTitle, DialogContent, DialogActions,TextField
} from '@mui/material';
import { 
    // GET_PUBLIC_NOTICE_LIST, 
    SET_PUBLIC_NOTICE_STATUS_MARK_AS_PAID, 
    GET_PUBLIC_NOTICE_OFFLINE_PAYMENT_LIST,
    APPLICATION_UPDATE_DEMAND_NOTE_NO } 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 EditNoteIcon from '@mui/icons-material/EditNote';
import { useForm } from "react-hook-form";

// ==============================|| 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 [demandNoteNoPopUp, setDemandNoteNoPopUp] = React.useState(false);
    // const [confirmDemandNoteNoPopUp, setConfirmDemandNoteNoPopUp] = React.useState(false);
    const [demandNoteNo, setDemandNoteNo] = React.useState();
    const [demandNoteNoId, setDemandNoteNoId] = React.useState();
    
    const { register, handleSubmit } = useForm()

    const [refreshTrigger, setRefreshTrigger] = React.useState(0);
    const forceRefresh = () => {
        setRefreshTrigger(prev => prev + 1);
    };

    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
    }

    function updateDemandNoteNo(id, remark) {
        setDemandNoteNoId(id)
        setDemandNoteNo(remark)
        doDemandNoteNo()
        // setConfirmDemandNoteNoPopUp(true)
    }
    
    function editDemandNoteNo(id, remark) {
        setDemandNoteNoId(id)
        setDemandNoteNo(remark)
        setDemandNoteNoPopUp(true)
    }

    const doDemandNoteNo = () => {
        // setConfirmDemandNoteNoPopUp(false);
        console.log(refreshTrigger)
        HttpUtils.post({
            url: APPLICATION_UPDATE_DEMAND_NOTE_NO + "/" + demandNoteNoId,
            params:{
                demandNoteNo:demandNoteNo
            },
            onSuccess: function () {
                forceRefresh()
            }
        });
    }

    const onSubmit = (data) => {
        // console.log(data)
        const formDemandNoteNo = data.formDemandNoteNo
        if (formDemandNoteNo != null) {
            HttpUtils.post({
                url: APPLICATION_UPDATE_DEMAND_NOTE_NO + "/"+ demandNoteNoId,
                params: {
                    demandNoteNo:formDemandNoteNo
                },
                onSuccess: function () {
                    setDemandNoteNoPopUp(false)
                    forceRefresh()
                }
            });
        } else {
            setDemandNoteNoPopUp(false)
        }

    };

    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: 'contactPerson',
            field: 'contactPerson',
            headerName: 'Customer Name',
            flex: 1,
            minWidth: 50,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                let company = params.row.enCompanyName != null ? params.row.enCompanyName : params.row.chCompanyName;
                company = company != null ? company : "";
                if (params.row.sysType != null && params.row.sysType == "dummy"){
                    company =  params.row.contactPerson
                }
                return <div>
                    {params?.value}<br />{company}
                </div>;
            }
        },
        {
            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>

            )
        },
        {
            id: 'paymentMethod',
            field: 'paymentMethod',
            headerName: 'Payment Means',
            sortable: false,
            minWidth: 250,
            flex: 2,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {
                let paymentMethod = params.row.paymentMethod!=null?intl.formatMessage({ id: utils.getPaymentMethod(params.row.paymentMethod)}):""
                return (<>
                    {paymentMethod}
                </>);
            }
        },
        {
            id: 'fee',
            field: 'fee',
            headerName: 'Amount($)',
            flex: 1,
            minWidth: 100,
            renderHeader: renderHeaderWithAria,
            valueGetter: (params) => {
                return FormatUtils.currencyFormat(params?.value);
            }
        },
        {
            id: 'demandNoteNo',
            field: 'demandNoteNo',
            headerName: 'Remarks',
            flex: 2,
            minWidth: 200,
            renderHeader: renderHeaderWithAria,
            renderCell: (params) => {            
                const handleBlur = (event) => {
                    const newValue = event.target.value;
                    updateDemandNoteNo(params.row.id, newValue);
                };
        
                return (
                    <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                        {
                            params.row.demandNoteNo?
                                <Stack direction="row" justifyContent="space-between" alignItems="center" width="100%">
                                    {params.row.demandNoteNo}
                                    <Button
                                        // size="small"
                                        variant="contained"
                                        onClick={() => editDemandNoteNo(params.row.id, params.row.demandNoteNo)}
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end',

                                        }}>
                                        <EditNoteIcon />
                                        {/* <Typography ml={1} variant="h5"> Edit</Typography> */}
                                    </Button>
                                </Stack>
                            :
                                <Stack direction="row" justifyContent="space-between" alignItems="center" width="100%">
                                    <TextField
                                        size="small"
                                        variant="outlined"
                                        defaultValue={params.row.demandNoteNo || ''}
                                        onBlur={handleBlur}
                                        placeholder="Enter Demand Note No."
                                        InputProps={{
                                            style: { height: '32px', fontSize: '0.875rem' }
                                        }}
                                        sx={{
                                            '& .MuiOutlinedInput-root': { height: '32px' },
                                            flex: 1,
                                            minWidth: '60px'
                                        }}
                                    />
                                    <Button
                                        // size="small"
                                        variant="contained"
                                        onClick={() => updateDemandNoteNo(params.row.id, params.row.demandNoteNo)}
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end',

                                        }}>
                                        save
                                        {/* <Typography ml={1} variant="h5"> Edit</Typography> */}
                                    </Button>
                                </Stack>
                        }
                    </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_MARK_AS_PAID,
                params: {
                    ids: appIdList
                },
                onSuccess: () => {
                    searchCriteria.reload = new Date();
                    notifyActionSuccess("Action Success!")
                    location.reload()
                }
            });
        }
    }

    return (<>

        <div style={{ width: '100%' }}>
            <Grid container direction="row" justifyContent="flex-start" alignItems="center" sx={{ p: 1 }} >
                <Button
                    variant="contained"
                    onClick={() => setIsConfirmPopUp(true)}
                >
                    Mark as Paid
                </Button>
            </Grid>

            <FiDataGrid
                checkboxSelection
                disableRowSelectionOnClick
                onRowSelectionModelChange={(newSelection) => {
                    setSelectedRowItems(newSelection);
                }}
                isRowSelectable={(params) => {
                    return (params.row.paymentMethod != "online" && params.row.status == "confirmed")
                }}
                columns={columns}
                customPageSize={10}
                getRowHeight={() => 'auto'}
                onRowDoubleClick={handleRowDoubleClick}
                applyGridOnReady={applyGridOnReady}
                applySearch={applySearch}
                doLoad={React.useMemo(() => ({
                    url: GET_PUBLIC_NOTICE_OFFLINE_PAYMENT_LIST,
                    params: _searchCriteria,
                    callback: function (responseData) {
                        setRows(responseData?.records);
                    }
                }), [_searchCriteria, refreshTrigger])}
            />
        </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 Paid.</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>
        {/* <div>
            <Dialog
                open={confirmDemandNoteNoPopUp}
                onClose={() => setConfirmDemandNoteNoPopUp(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' }}> Confirm Demand Note No. : {demandNoteNo}? </Typography>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setConfirmDemandNoteNoPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                    <Button onClick={() => doDemandNoteNo()}><Typography variant="h5">Confirm</Typography></Button>
                </DialogActions>
            </Dialog>
        </div> */}
        <div>
            <Dialog
                open={demandNoteNoPopUp}
                onClose={() => setDemandNoteNoPopUp(false)}
                PaperProps={{
                    sx: {
                        minWidth: '40vw',
                        maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                        maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                    }
                }}
            >
                <form onSubmit={handleSubmit(onSubmit)}>
                    <DialogTitle><Typography variant="h3">Remarks</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Grid container direction="column">
                            <Grid item sx={{ padding: '16px' }}>
                                <TextField
                                    fullWidth
                                    {...register("formDemandNoteNo")}
                                    id='formDemandNoteNo'
                                    // label="Remarks"
                                    defaultValue={demandNoteNo}
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            </Grid>
                        </Grid>

                    </DialogContent>
                    <DialogActions>
                        <Stack direction="row" justifyContent="space-between">
                            <Button onClick={() => setDemandNoteNoPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                            <Button type="submit"><Typography variant="h5">Save</Typography></Button>
                            {/* <Button onClick={() => markAsCreditor()}><Typography variant="h5">Confirm</Typography></Button> */}
                        </Stack>
                    </DialogActions>
                </form>
            </Dialog>
        </div>
    </>

    );
}
