// material-ui
import {
    FormControl,
    Button,
    Grid,
    Typography, FormLabel,
    OutlinedInput,
    Stack,
    Dialog, DialogTitle, DialogContent, DialogActions, InputAdornment,
} from '@mui/material';
const MainCard = Loadable(lazy(() => import('components/MainCard')));
import { useForm } from "react-hook-form";
import {
    useEffect,
    useState
} from "react";

import Loadable from 'components/Loadable';

import { lazy } from 'react';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
import * as HttpUtils from "utils/HttpUtils"
import * as UrlUtils from "utils/ApiPathConst"
import * as StatusUtils from "utils/statusUtils/PublicNoteStatusUtils";

import DoneIcon from '@mui/icons-material/Done';
import CloseIcon from '@mui/icons-material/Close';
import EditNoteIcon from '@mui/icons-material/EditNote';
import DownloadIcon from '@mui/icons-material/Download';
import ReplayIcon from '@mui/icons-material/Replay';
import { notifyDownloadSuccess } from 'utils/CommonFunction';

// ==============================|| DASHBOARD - DEFAULT ||============================== //
const ApplicationDetailCard = (
    { applicationDetailData,
        setStatus,
        setUploadStatus
    }
) => {

    const [currentApplicationDetailData, setCurrentApplicationDetailData] = useState({});
    const [companyName, setCompanyName] = useState({});
    const [verified, setVerified] = useState(null);
    const [fileDetail, setfileDetail] = useState({});
    const [onReady, setOnReady] = useState(false);

    const { register } = useForm()

    const [isWarningPopUp, setIsWarningPopUp] = useState(false);
    const [warningText, setWarningText] = useState("");

    useEffect(() => {
        //if user data from parent are not null
        // console.log(applicationDetailData)
        if (Object.keys(applicationDetailData).length > 0) {
            loadApplicationDetail()
        }
    }, [applicationDetailData]);

    useEffect(() => {
        //if state data are ready and assign to different field
        // console.log(currentApplicationDetailData)
        if (Object.keys(currentApplicationDetailData).length > 0) {
            setOnReady(true);
        }
    }, [currentApplicationDetailData]);

    const loadApplicationDetail = () => {
        setCurrentApplicationDetailData(applicationDetailData.data);
        setCompanyName(applicationDetailData.companyName);
        setVerified(applicationDetailData.userData.verifiedBy ? true : false)
        setfileDetail(applicationDetailData.fileDetail);
        // setReload(false)
    }

    const onDownloadClick = () => () => {
        HttpUtils.fileDownload({
            fileId: fileDetail.id,
            skey: fileDetail.skey,
            filename: fileDetail.filename,
        });
        notifyDownloadSuccess()
        setUploadStatus(true)
    };


    const reSubmitClick = () => () => {
        setStatus("resubmit")
    };

    const notAcceptedClick = () => () => {
        setStatus("notAccepted")
    };

    const complatedClick = () => () => {
        setStatus("complete")
    };

    const withdrawnClick = () => () => {
        setStatus("withdraw")
    };

    const doPublish =()=>()=>{
        setStatus("publish")
    }

    const onProofClick = () => {
        if (applicationDetailData.data.groupNo) {
            HttpUtils.get({
                url: UrlUtils.CHECK_CREATE_PROOF + "/" + currentApplicationDetailData.id,
                onSuccess: function (responeData) {
                    if (responeData.success == true) {
                        window.open("/proof/create/" + currentApplicationDetailData.id, "_blank", "noreferrer");
                        window.addEventListener("focus", onFocus)
                    } else {
                        let msg = responeData.msg;
                        if (msg === "haveActiveProof") {
                            msg = "Action Failed: There is already a pending payment and proofreading record for client review."
                        } else if (msg === "haveProofed") {
                            msg = "Action Failed: Already proofed."
                        }
                        setWarningText(msg);
                        setIsWarningPopUp(true);
                    }
                }
            });

        } else {
            setWarningText("Please generate Gazette Code before Create Proof.");
            setIsWarningPopUp(true);
        }

    }

    const onFocus = () => {
        location.reload();
        window.removeEventListener("focus", onFocus)
    }

    return (
        !onReady ?
            <LoadingComponent />
            :
            <MainCard elevation={0}
                border={false}
                content={false}
            >
                {verified && currentApplicationDetailData.status !== "notAccepted" ?
                    <Grid container spacing={4} direction="row">
                        <Grid item xs={12} md={4} >
                            <Stack
                                direction="row"
                                justifyContent="flex-start"
                                alignItems="center"
                                spacing={2}
                                mb={2}
                            >
                                {currentApplicationDetailData.status === "reviewed" ?
                                    <Button
                                        // size="large"
                                        variant="contained"
                                        onClick={() => { onProofClick() }}
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end'
                                        }}>
                                        <EditNoteIcon />
                                        <Typography ml={1} variant="h5"> Create Proof</Typography>
                                    </Button> :
                                    null
                                }
                            </Stack>
                        </Grid>
                        <Grid item xs={12} md={8} >
                            <Stack
                                direction="row"
                                justifyContent="flex-start"
                                alignItems="center"
                                spacing={2}
                                mb={2}
                            >
                                {currentApplicationDetailData.status === "submitted" || currentApplicationDetailData.status == "reviewed" ?
                                    <>
                                        <Button
                                            // size="large"
                                            variant="contained"
                                            onClick={reSubmitClick()}
                                            color="orange"
                                        >
                                            <ReplayIcon />
                                            <Typography ml={1} variant="h5"> Re-submit</Typography>
                                        </Button>
                                        <Button
                                            // size="large"
                                            variant="contained"
                                            onClick={notAcceptedClick()}
                                            color="error"
                                            sx={{
                                                textTransform: 'capitalize',
                                                alignItems: 'end',
                                            }}>
                                            <CloseIcon />
                                            <Typography ml={1} variant="h5">Not accept</Typography>
                                        </Button>
                                    </> :
                                    (currentApplicationDetailData.status == "confirmed" && currentApplicationDetailData.creditor == 1) ?
                                        <>
                                            <Button
                                                // size="large"
                                                variant="contained"
                                                onClick={doPublish()}
                                                sx={{
                                                    textTransform: 'capitalize',
                                                    alignItems: 'end',
                                                    backgroundColor: '#52b202'
                                                }}>
                                                <DoneIcon />
                                                <Typography ml={1} variant="h5">Publish</Typography>
                                            </Button>
                                        </>
                                        :
                                        (currentApplicationDetailData.status == "paid" && currentApplicationDetailData.creditor == 0) ?
                                            <>
                                                <Button
                                                    // size="large"
                                                    variant="contained"
                                                    onClick={complatedClick()}
                                                    sx={{
                                                        textTransform: 'capitalize',
                                                        alignItems: 'end',
                                                        backgroundColor: '#52b202'
                                                    }}>
                                                    <DoneIcon />
                                                    <Typography ml={1} variant="h5">Complete</Typography>
                                                </Button>
                                                <Button
                                                    // size="large"
                                                    variant="contained"
                                                    onClick={withdrawnClick()}
                                                    sx={{
                                                        textTransform: 'capitalize',
                                                        alignItems: 'end',
                                                        backgroundColor: '#ffa733'
                                                    }}>
                                                    <CloseIcon />
                                                    <Typography ml={1} variant="h5">Withdraw</Typography>
                                                </Button>
                                            </> : null
                                }
                            </Stack>
                        </Grid>
                    </Grid> : null
                }
                <Typography variant="h4" xs={12} md={12} sx={{ mb: 2, borderBottom: "1px solid black" }}>
                    Application Details
                </Typography>
                <form>
                    <Grid container direction="column">
                        <Grid item xs={12} md={12}>
                            <Grid container direction="row" justifyContent="flex-start"
                                alignItems="center">
                                <Grid item xs={12} md={6} lg={6} sx={{ mb: 1 }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={4} lg={4}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="h5">Application No:</Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={8} lg={8}>
                                            <FormControl variant="outlined" fullWidth disabled >
                                                <OutlinedInput
                                                    fullWidth
                                                    size="small"
                                                    {...register("appNo",
                                                        {
                                                            value: currentApplicationDetailData.appNo,
                                                        })}
                                                    id='appNo'
                                                    sx={{
                                                        "& .MuiInputBase-input.Mui-disabled": {
                                                            WebkitTextFillColor: "#000000",
                                                            background: "#f8f8f8",
                                                        },
                                                    }}
                                                />
                                            </FormControl>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid item xs={12} sm={12} md={5.5} lg={5.5} sx={{ mb: 1, ml: { md: 1, lg: 3 } }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={4} lg={4}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="h5">Status:</Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={8} lg={8}>
                                            <FormControl variant="outlined">
                                                {StatusUtils.getStatusByTextEng(currentApplicationDetailData.status)}
                                            </FormControl>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid container direction="row" justifyContent="flex-start"
                                alignItems="center">
                                <Grid item xs={12} md={6} lg={6} sx={{ mb: 1 }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={4} lg={4}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="h5">Applicant:</Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={8} lg={8}>
                                            <FormControl variant="outlined" fullWidth disabled >
                                                {currentApplicationDetailData.orgId === null ?
                                                    <OutlinedInput
                                                        fullWidth
                                                        size="small"
                                                        {...register("contactPerson",
                                                            {
                                                                value: currentApplicationDetailData.contactPerson,
                                                            })}
                                                        id='contactPerson'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                    /> :
                                                    <OutlinedInput
                                                        fullWidth
                                                        size="small"
                                                        {...register("companyName",
                                                            {
                                                                value: companyName.enCompanyName,
                                                            })}
                                                        id='companyName'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                    />
                                                }
                                            </FormControl>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid item xs={12} md={5.5} lg={5.5} sx={{ mb: 1, ml: { md: 1, lg: 3 } }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={4} lg={4}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="h5">Contact Phone:</Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={8} lg={8}>
                                            <Stack direction="row">
                                                <FormControl variant="outlined" sx={{ width: '25%' }} disabled >
                                                    <OutlinedInput
                                                        size="small"
                                                        {...register("contactTelNo.countryCode",
                                                            {
                                                                value: currentApplicationDetailData.contactTelNo.countryCode,
                                                            })}
                                                        id='countryCode'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                            mr: 1
                                                        }}
                                                        inputProps={{
                                                            maxLength: 3,
                                                        }}
                                                        endAdornment={<InputAdornment position="end">-</InputAdornment>}
                                                    />
                                                </FormControl>
                                                <FormControl variant="outlined" sx={{ width: '75%' }} disabled >
                                                    <OutlinedInput
                                                        size="small"
                                                        type="tel"
                                                        {...register("contactTelNo.phoneNumber",
                                                            {
                                                                value: currentApplicationDetailData.contactTelNo.phoneNumber,
                                                            })}
                                                        id='phoneNumber'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                        inputProps={{
                                                            maxLength: 11,
                                                        }}
                                                    />
                                                </FormControl>
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid container direction="row" justifyContent="flex-start"
                                alignItems="center">
                                <Grid item xs={12} md={6} lg={6} sx={{ mb: 1 }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={4} lg={4}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="h5">Contact Person:</Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={8} lg={8}>
                                            <FormControl variant="outlined" fullWidth disabled>
                                                <OutlinedInput
                                                    fullWidth
                                                    size="small"
                                                    {...register("contactPerson",
                                                        {
                                                            value: currentApplicationDetailData.contactPerson,
                                                        })}
                                                    id='contactPerson'
                                                    sx={{
                                                        "& .MuiInputBase-input.Mui-disabled": {
                                                            WebkitTextFillColor: "#000000",
                                                            background: "#f8f8f8",
                                                        },
                                                    }}
                                                />
                                            </FormControl>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid item xs={12} md={5.5} lg={5.5} sx={{ mb: 1, ml: { md: 1, lg: 3 } }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={4} lg={4}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="h5">Contact Fax:</Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={8} lg={8}>
                                            <Stack direction="row">
                                                <FormControl variant="outlined" sx={{ width: '25%' }} disabled>
                                                    <OutlinedInput
                                                        size="small"
                                                        {...register("contactFaxNo.countryCode",
                                                            {
                                                                value: currentApplicationDetailData.contactFaxNo.countryCode,
                                                            })}
                                                        id='countryCode'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                            mr: 1,
                                                        }}
                                                        inputProps={{
                                                            maxLength: 3,
                                                            type: "tel"
                                                        }}
                                                        endAdornment={<InputAdornment position="end">-</InputAdornment>}
                                                    />
                                                </FormControl>
                                                <FormControl variant="outlined" sx={{ width: '75%' }} disabled>
                                                    <OutlinedInput
                                                        size="small"
                                                        type="tel"
                                                        {...register("contactFaxNo.faxNumber",
                                                            {
                                                                value: currentApplicationDetailData.contactFaxNo.faxNumber,
                                                            })}
                                                        id='faxNumber'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                        inputProps={{
                                                            maxLength: 8,
                                                        }}
                                                    />
                                                </FormControl>
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid container direction="row" justifyContent="flex-start"
                                alignItems="center">
                                <Grid item xs={12} md={12} lg={12} mt={1} >
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={12} lg={12}>
                                            <Grid container direction="row">
                                                <Grid item xs={12} md={2} lg={2}
                                                    sx={{ display: 'flex', alignItems: 'center' }}>
                                                    <FormLabel><Typography variant="h5" >Manuscript File:</Typography></FormLabel>
                                                </Grid>
                                                <Grid item xs={12} md={8} lg={8} sx={{ display: 'flex', alignItems: 'center' }}>
                                                    <Grid container direction="row" justifyContent="flex-start">
                                                        <Grid item xs={10} md={8} lg={8} sx={{ display: 'flex', alignItems: 'center' }}>
                                                            <FormControl variant="outlined" fullWidth  >
                                                                <Typography
                                                                    // fullWidth
                                                                    id='fileName'
                                                                    variant="h5"
                                                                    sx={{ wordBreak: 'break-word' }}
                                                                >
                                                                    {fileDetail.filename}
                                                                </Typography>
                                                            </FormControl>
                                                        </Grid>
                                                        <Grid item md={2} lg={2}>
                                                            <Button
                                                                size="small"
                                                                variant="contained"
                                                                onClick={onDownloadClick()}
                                                                sx={{
                                                                    textTransform: 'capitalize',
                                                                    alignItems: 'end',
                                                                }}>
                                                                <DownloadIcon />
                                                            </Button>
                                                        </Grid>
                                                    </Grid>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </form>
                <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' }}>{warningText}</Typography>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setIsWarningPopUp(false)}><Typography variant="h5">OK</Typography></Button>
                        </DialogActions>
                    </Dialog>
                </div>
            </MainCard>
    );
};

export default ApplicationDetailCard;
