// material-ui
import {
    FormControl,
    Grid,
    Typography,
    FormLabel,
    TextField,
    Button,
    Stack,
    Dialog, DialogTitle, DialogContent, DialogActions,
    CircularProgress,
} from '@mui/material';

import { useFormik } from 'formik';
import { useIntl } from 'react-intl';
import {isGranted} from "auth/utils";
import {useState, useEffect, useRef, lazy} from "react";
import * as HttpUtils from "utils/HttpUtils"
import * as UrlUtils from "utils/ApiPathConst"
import * as DateUtils from "utils/DateUtils"
import * as FormatUtils from "utils/FormatUtils"
import { useParams } from "react-router-dom";
import Loadable from 'components/Loadable';
const MainCard = Loadable(lazy(() => import('components/MainCard')));
import * as StatusUtils from "utils/statusUtils/PublicNoteStatusUtils";
import FileList from "components/FileList"
// ==============================|| DASHBOARD - DEFAULT ||============================== //
const ApplicationDetailCard = ({
    formData,
    showCancelBtn,
    showProofBtn
    // setBackButtonPos 
}) => {

    const params = useParams();
    const intl = useIntl();

    const [data, setData] = useState({});
    const [cancelPopUp, setCancelPopUp] = useState(false);
    const [cancelLoading, setCancelLoading] = useState(false);
    const cancellingRef = useRef(false);
    const [onDownload, setOnDownload] = useState(false);
    const [alertMsg, setAlertMsg] = useState('');
    const [showAlert, setShowAlert] = useState(false);

    useEffect(() => {
        if (formData) {
            setData(formData);
        }
    }, [formData]);

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: data,
    });

    const DisplayField = ({ name, width, dummyUser }) => {
        return <>
            {dummyUser?
                <TextField
                    fullWidth
                    disabled
                    size="small"
                    onChange={formik.handleChange}
                    id={name}
                    name={name}
                    value={"GLD: "+formik.values[name]}
                    variant="outlined"
                    sx={
                        {
                            "& .MuiInputBase-input.Mui-disabled": {
                                WebkitTextFillColor: "#000000",
                                background: "#f8f8f8",
                            },
                            width: width ? width : '100%'
                        }
                    }
                />
            :
                <TextField
                    fullWidth
                    disabled
                    size="small"
                    onChange={formik.handleChange}
                    id={name}
                    name={name}
                    value={formik.values[name]}
                    variant="outlined"
                    sx={
                        {
                            "& .MuiInputBase-input.Mui-disabled": {
                                WebkitTextFillColor: "#000000",
                                background: "#f8f8f8",
                            },
                            width: width ? width : '100%'
                        }
                    }
                />
            }
        </> 
    }

    const confirmCancel = () => {
        if (cancellingRef.current) return;
        cancellingRef.current = true;
        setCancelLoading(true);
        HttpUtils.get({
            url: UrlUtils.CANCEL_PROOF + "/" + params.id,
            onSuccess: function (responseData) {
                cancellingRef.current = false;
                setCancelLoading(false);
                if (responseData && responseData.success === false) {
                    setCancelPopUp(false);
                    const msg = responseData.msg ? intl.formatMessage({ id: responseData.msg }) : intl.formatMessage({ id: 'proofAlreadyCancelled' });
                    setAlertMsg(msg);
                    setShowAlert(true);
                } else {
                    window.location.reload(false);
                }
            },
            onFail: () => {
                cancellingRef.current = false;
                setCancelLoading(false);
            },
            onError: () => {
                cancellingRef.current = false;
                setCancelLoading(false);
            }
        });
    }

    const doCancel = () => {
        setCancelPopUp(true);
    }

    const genProof = () => {
        setOnDownload(true)
        HttpUtils.fileDownload({
            url: UrlUtils.GEN_GAZETTE_PROOF + "/" + params.id,
            onResponse:()=>{
                setOnDownload(false)
            },
            onError:()=>{
                setOnDownload(false)
            }
        });
    }

    return (
        <MainCard
            id={"applicationDetailsMainCard"}
            border={false}
            content={false}
        >
            <Typography variant="h4" sx={{ textAlign: "left", mb: 2, borderBottom: "1px solid black" }}>
                <Stack
                    direction="row"
                    justifyContent="space-between"
                    alignItems="center"
                >
                    Public Notice: Proofreading Reply
                    {data.appMode != "offline"?
                        <>
                            <Button
                                component="span"
                                variant="contained"
                                size="large"
                                disabled={!showProofBtn||onDownload}
                                onClick={genProof}
                            >
                                <Typography variant="h5">Proof Slip</Typography>
                            </Button>
                            {
                                isGranted(["MAINTAIN_PROOF"]) ? <Button
                                    component="span"
                                    variant="contained"
                                    size="large"
                                    color="error"
                                    disabled={showCancelBtn}
                                    onClick={doCancel}
                                >
                                    <Typography variant="h5">Cancel</Typography>
                                </Button> : <></>
                            }
                        </>        
                        :null
                    }

                </Stack>

            </Typography>
            <form>
                <Grid container direction="column">
                    <Grid item xs={12} md={12} lg={12}>
                        <Grid container direction="row" justifyContent="space-between"
                            alignItems="center">
                            <Grid item xs={12} md={6} lg={6} sx={{ mb: 1 }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel><Typography variant="h5">App. No.:</Typography></FormLabel>
                                    </Grid>

                                    <Grid item xs={12} md={9} lg={9}>
                                        <DisplayField name="appNo" />
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid item xs={12} md={5} lg={5} sx={{ mb: 1, ml: 1 }}>
                                <Grid container alignItems={"left"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel><Typography variant="h5">App. Status:</Typography></FormLabel>
                                    </Grid>

                                    <Grid item xs={12} md={9} lg={9} sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormControl variant="outlined">
                                            {StatusUtils.getStatusByTextEng(data.appStatus, data.creditor)}
                                        </FormControl>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid container direction="row" justifyContent="space-between"
                            alignItems="center">
                            <Grid item xs={12} md={6} lg={6} sx={{ mb: 1 }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel><Typography variant="h5">Applicant:</Typography></FormLabel>
                                    </Grid>

                                    <Grid item xs={12} md={9} lg={9}>
                                        <FormControl variant="outlined" fullWidth disabled >
                                            {data?.orgId?
                                                <DisplayField 
                                                    name="applicant" 
                                                    dummyUser={data?.enCompanyName == "GLD" ? true : false}/>
                                                :
                                                <DisplayField name="contactPerson" />
                                            }
                                        </FormControl>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid item xs={12} md={5} lg={5} sx={{ mb: 1, ml: 1 }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel><Typography variant="h5">Issue No:</Typography></FormLabel>
                                    </Grid>

                                    <Grid item xs={12} md={9} lg={9}>
                                        <DisplayField name="issueNoStr" />
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid container direction="row" justifyContent="space-between"
                            alignItems="center">
                            <Grid item xs={12} md={6} lg={6} sx={{ mb: 1 }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel><Typography variant="h5">Contact Person:</Typography></FormLabel>
                                    </Grid>

                                    <Grid item xs={12} md={9} lg={9}>
                                        <DisplayField name="contactPerson" />

                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid item xs={12} md={5} lg={5} sx={{ mb: 1, ml: 1 }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel><Typography variant="h5">Issue Date:</Typography></FormLabel>
                                    </Grid>

                                    <Grid item xs={12} md={9} lg={9}>
                                        <DisplayField name="issueDateStr" />
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                        {/* <Grid container direction="row" justifyContent="space-between"
                            alignItems="center">
                            <Grid item xs={12} md={6} lg={6} sx={{ mb: 1, }}>
                                <Grid container alignItems="left">
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel>Remarks:</FormLabel>
                                    </Grid>

                                    <Grid item xs={12} md={9} lg={9}>
                                        <Stack direction="row">
                                            <DisplayField name="appRemarks" />
                                        </Stack>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid> */}

                        <Grid container direction="row" justifyContent="space-between"
                            alignItems="center">

                            <Grid item xs={12} md={6} lg={6} sx={{ mb: 1, }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={12} lg={12} sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Print file：</Typography>
                                    </Grid>
                                </Grid>
                                <FileList
                                    refId={params.id}
                                    refType={"proof"}
                                    dateHideable={true}
                                    disablePagination
                                    disableSelectionOnClick
                                    disableColumnMenu
                                    disableColumnSelector
                                    hideFooter
                                />
                            </Grid>

                            <Grid item xs={12} md={4} lg={4} sx={{ mb: 1, }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={12} lg={12}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Deadline for proof with revision：</Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 4, display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Before {DateUtils.datetimeStr(data.reviseDeadline)}</Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Deadline for confirm proof and payment：</Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 4, display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Before {DateUtils.datetimeStr(data.proofPaymentDeadline)}</Typography>
                                    </Grid>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ mb: 1, display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Fee:</Typography>
                                    </Grid>
                                    <Grid item xs={12} md={9} lg={9} sx={{ mb: 1, display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5" style={{ color: "blue", fontWeight: "bold", }}>{FormatUtils.currencyFormat(data.fee)}</Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 4, display: 'flex', alignItems: 'center' }}>
                                        {
                                            formik.values.groupType == "Private Bill"
                                                ?
                                                <Typography variant="h5">( {data.noOfPages} page x $6,552 )</Typography>
                                                :
                                                <Typography variant="h5">( {data.length} cm x {data.colCount == 2 ? "$364 Double Column" : "$182 Single Column"} )</Typography>
                                        }
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>

                    </Grid>
                </Grid>
                <div>
                    <Dialog
                        open={cancelPopUp}
                        onClose={() => {
                            if (cancelLoading) return;
                            setCancelPopUp(false);
                        }}
                    >
                        <DialogTitle><Typography variant="h3">Confirm</Typography></DialogTitle>
                        <DialogContent style={{ display: 'flex', }}>
                            <Typography variant="h4" style={{ padding: '16px' }}>Are you sure you want to cancel this proof?</Typography>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setCancelPopUp(false)} disabled={cancelLoading}><Typography variant="h5">Cancel</Typography></Button>
                            <Button
                                onClick={() => confirmCancel()}
                                disabled={cancelLoading}
                                startIcon={cancelLoading ? <CircularProgress color="inherit" size={20} /> : null}
                            >
                                <Typography variant="h5">Confirm</Typography>
                            </Button>
                        </DialogActions>
                    </Dialog>
                    <Dialog open={showAlert} onClose={() => setShowAlert(false)}>
                        <DialogTitle><Typography variant="h3">{intl.formatMessage({ id: 'attention' })}</Typography></DialogTitle>
                        <DialogContent>
                            <Typography variant="h4" style={{ padding: '16px' }}>{alertMsg}</Typography>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setShowAlert(false)}><Typography variant="h5">OK</Typography></Button>
                        </DialogActions>
                    </Dialog>
                </div>
            </form>
        </MainCard>
    );
};

export default ApplicationDetailCard;
