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

import { lazy } from 'react';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
// import {useParams} from "react-router-dom";
import * as HttpUtils from "utils/HttpUtils"
import * as UrlUtils from "utils/ApiPathConst"
import * as StatusUtils from "utils/statusUtils/PublicNoteStatusUtils";
import * as DateUtils from "utils/DateUtils";
import * as FormatUtils from "utils/FormatUtils";
import {
    isORGLoggedIn,
} from "utils/Utils";

// import BorderColorOutlinedIcon from '@mui/icons-material/BorderColorOutlined';
// 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 {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import * as React from "react";
import {FormattedMessage, useIntl} from "react-intl";
// ==============================|| DASHBOARD - DEFAULT ||============================== //
const ApplicationDetailCard = (
    { applicationDetailData,
        setStatus,
        // updateUserObject,
        // isNewRecord
    }
) => {
    const [isPopUp, setIsPopUp] = useState(false);
    const [errorText, setErrorText] = useState("");
    const [errorPopUp, setErrorPopUp] = useState(false);
    // const params = useParams();
    const [currentApplicationDetailData, setCurrentApplicationDetailData] = useState({});
    const [fee, setFee] = useState(0);
    const [companyName, setCompanyName] = useState({});
    const [fileDetail, setfileDetail] = useState({});
    const [onReady, setOnReady] = useState(false);
    const [issueNum, setIssueNum] = useState("");
    const [issueDate, setIssueDate] = useState("");
    const { register,
        // getValues
    } = useForm();
    const navigate = useNavigate();
    const intl = useIntl();

    useEffect(() => {
        //if user data from parent are not null
        // console.log(applicationDetailData)
        if (Object.keys(applicationDetailData).length > 0 && applicationDetailData.data !== null) {
            setCurrentApplicationDetailData(applicationDetailData.data);
            setCompanyName(applicationDetailData.companyName);
            setfileDetail(applicationDetailData.fileDetail);
            setIssueNum(applicationDetailData.gazetteIssueDetail.volume + "/" + applicationDetailData.gazetteIssueDetail.year
                + " No. " + applicationDetailData.gazetteIssueDetail.issueNo);
            setIssueDate(DateUtils.dateFormat(applicationDetailData.gazetteIssueDetail.issueDate, "D MMM YYYY (ddd)"));

            for (let i = 0; i < applicationDetailData.proofList.length; i++) {
                if (applicationDetailData.proofList[i].action == true) {
                    setFee(applicationDetailData.proofList[i].fee);
                }
            }
        }
    }, [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 onDownloadClick = () => () => {
        HttpUtils.fileDownload({
            fileId: fileDetail.id,
            skey: fileDetail.skey,
            filename: fileDetail.filename,
        });
    };

    const cancelledClick = () => () => {
        setStatus("cancel")
    };

    const checkExprityDate = () => {
        HttpUtils.post({
            url: UrlUtils.POST_CHECK_APP_EXPRITY_DATE,
            params: {
                ids: [currentApplicationDetailData.id]
            },
            onSuccess: (responData) => {
                if (responData.success == true) {
                    setIsPopUp(true);
                    return;
                }
                setErrorText("公共啟事申請已過期");
                setErrorPopUp(true);
            }
        });
    };


    function doPayment() {
        setIsPopUp(false);
        navigate('/paymentPage', { state: { amount: fee, appIdList: [currentApplicationDetailData.id] } });
    }

    return (
        !onReady ?
            <LoadingComponent />
            :
            <MainCard elevation={0}
                border={false}
                content={false}
            >
                <Grid container spacing={1} direction="row">
                    <Grid item xs={12}>
                        <Stack
                            direction="row"
                            justifyContent="space-between"
                            alignItems="center"
                            spacing={2}
                            mb={2}
                        >
                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                            {
                                currentApplicationDetailData.status == "confirmed" ?
                                    <Button
                                        variant="contained"
                                        color="create"
                                        onClick={() => { checkExprityDate(true) }}
                                        disabled={currentApplicationDetailData.status == "rejected"
                                            || currentApplicationDetailData.status == "cancelled"
                                            || currentApplicationDetailData.status == "paid"
                                            || currentApplicationDetailData.creditor}
                                        startIcon={<EditNoteIcon />}
                                        aria-label={intl.formatMessage({id: 'payFor'})}
                                    >
                                        <FormattedMessage id="payFor"/>
                                    </Button>
                                    : null
                            }
                            <Button
                                variant="contained"
                                onClick={cancelledClick()}
                                color="edit"
                                disabled={currentApplicationDetailData.status !== "submitted"}
                                title={intl.formatMessage({id: 'cancel'})}
                                startIcon={<CloseIcon />}
                                aria-label={intl.formatMessage({id: 'cancel'})}
                            >
                                <FormattedMessage id="cancel"/>
                            </Button>
                            </ThemeProvider>
                        </Stack>
                    </Grid>
                </Grid>
                <Typography variant="h4" sx={{ mb: 2, borderBottom: "1px solid black" }}>
                    <FormattedMessage id="publicNoticeDetailTitle"/>
                </Typography>
                <form>
                    <Grid container direction="column">
                        <Grid item xs={12} md={12}>
                            <Grid container direction="row" justifyContent="space-between"
                                alignItems="center">
                                <Grid item xs={12} sm={12} md={9} 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="pnspsFormParagraph">
                                                <FormattedMessage id="applicationId"/>:
                                            </Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={9} lg={9}>
                                            <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={9} 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="pnspsFormParagraph">
                                                <FormattedMessage id="applyStatus"/>:
                                            </Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={4} lg={4}>
                                            <FormControl variant="outlined">
                                                {currentApplicationDetailData.status? StatusUtils.getStatusByTextIntl(currentApplicationDetailData.status, false,intl) : ""}
                                            </FormControl>
                                        </Grid>
                                        {
                                            currentApplicationDetailData.reason ?
                                                <Grid item xs={12} md={5} lg={5}>
                                                    <Grid container alignItems={"center"}>
                                                        <Stack direction="row" justifyContent="flex-start" alignItems="center">
                                                            <Grid item xs={12} md={7} lg={7}>
                                                                <FormLabel><Typography variant="pnspsFormParagraph">原因:</Typography></FormLabel>
                                                            </Grid>
                                                            <Grid item xs={12} md={5} lg={5}>
                                                                <FormControl variant="outlined" fullWidth disabled>
                                                                    <Typography id='reason' variant="pnspsFormParagraph">
                                                                        {currentApplicationDetailData.reason}
                                                                    </Typography>
                                                                </FormControl>
                                                            </Grid>
                                                        </Stack>
                                                    </Grid>
                                                </Grid>
                                                : ""
                                        }
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid container direction="row" justifyContent="space-between"
                                alignItems="center">
                                <Grid item xs={12} sm={12} md={9} 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="pnspsFormParagraph">
                                                <FormattedMessage id="applyPerson"/>:
                                            </Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={9} lg={9}>
                                            <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} sm={12} md={9} lg={5} sx={{ mb: 1, ml: {lg:1} }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={3} lg={3}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="pnspsFormParagraph">
                                                <FormattedMessage id="gazetteCount"/>:
                                            </Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={9} lg={9}>
                                            <Stack direction="row">
                                                <FormControl variant="outlined" fullWidth disabled>
                                                    <OutlinedInput
                                                        size="small"
                                                        {...register("issueNum",
                                                            {
                                                                value: issueNum,
                                                            })}
                                                        id='issueNum'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                    />
                                                </FormControl>
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid container direction="row" justifyContent="space-between"
                                alignItems="center">
                                <Grid item xs={12} sm={12} md={9} 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="pnspsFormParagraph">
                                                <FormattedMessage id="contactPerson"/>:
                                            </Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={9} lg={9}>
                                            <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} sm={12} md={9} lg={5} sx={{ mb: 1, ml: {lg:1} }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={3} lg={3}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="pnspsFormParagraph">
                                                <FormattedMessage id="publishDate"/>:
                                            </Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={9} lg={9}>
                                            <Stack direction="row">
                                                <FormControl variant="outlined" fullWidth disabled>
                                                    <OutlinedInput
                                                        size="small"
                                                        {...register("issueDate",
                                                            {
                                                                value: issueDate,
                                                            })}
                                                        id='issueDate'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                    />
                                                </FormControl>
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>

                            <Grid container direction="row" justifyContent="space-between"
                                alignItems="center">
                                <Grid item xs={12} sm={12} md={9} 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="pnspsFormParagraph">
                                                <FormattedMessage id="userContactNumber"/>:
                                            </Typography></FormLabel>
                                        </Grid>

                                        <Grid item xs={12} md={9} lg={9}>
                                            <Stack direction="row">
                                                <FormControl variant="outlined" sx={{ width: '25%' }} disabled>
                                                    <OutlinedInput
                                                        size="small"
                                                        {...register("countryCode",
                                                            {
                                                                value: currentApplicationDetailData.contactTelNo.countryCode,
                                                            })}
                                                        id='countryCode'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                    />
                                                </FormControl>
                                                <FormControl variant="outlined" sx={{ width: '100%' }} disabled>
                                                    <OutlinedInput
                                                        size="small"
                                                        {...register("phoneNumber",
                                                            {
                                                                value: currentApplicationDetailData.contactTelNo.phoneNumber,
                                                            })}
                                                        id='phoneNumber'
                                                        sx={{
                                                            "& .MuiInputBase-input.Mui-disabled": {
                                                                WebkitTextFillColor: "#000000",
                                                                background: "#f8f8f8",
                                                            },
                                                        }}
                                                    />
                                                </FormControl>
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                {
                                    fee > 0 ?
                                        <Grid item xs={12} sm={12} md={9} 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="pnspsFormParagraph">
                                                        <FormattedMessage id="currencyPrice"/>(HK$):
                                                    </Typography></FormLabel>
                                                </Grid>

                                                <Grid item xs={12} md={9} lg={9}>
                                                    <FormLabel><Typography variant="pnspsFormParagraph">{FormatUtils.currencyFormat(fee)}</Typography></FormLabel>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                        :
                                        <></>
                                }

                            </Grid>
                            <Grid item xs={12} sm={12} md={9} 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="pnspsFormParagraph">
                                            <FormattedMessage id="userFaxNumber"/>:
                                        </Typography></FormLabel>
                                    </Grid>

                                    <Grid item xs={12} sm={12} md={9} lg={9}>
                                        <Stack direction="row">
                                            <FormControl variant="outlined" sx={{ width: '25%' }} disabled>
                                                <OutlinedInput
                                                    size="small"
                                                    {...register("countryCode",
                                                        {
                                                            value: currentApplicationDetailData.contactFaxNo.countryCode,
                                                        })}
                                                    id='countryCode'
                                                    sx={{
                                                        "& .MuiInputBase-input.Mui-disabled": {
                                                            WebkitTextFillColor: "#000000",
                                                            background: "#f8f8f8",
                                                        },
                                                    }}
                                                />
                                            </FormControl>
                                            <FormControl variant="outlined" sx={{ width: '100%' }} disabled>
                                                <OutlinedInput
                                                    size="small"
                                                    {...register("faxNumber",
                                                        {
                                                            value: currentApplicationDetailData.contactFaxNo.faxNumber,
                                                        })}
                                                    id='faxNumber'
                                                    sx={{
                                                        "& .MuiInputBase-input.Mui-disabled": {
                                                            WebkitTextFillColor: "#000000",
                                                            background: "#f8f8f8",
                                                        },
                                                    }}
                                                />
                                            </FormControl>
                                        </Stack>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid container direction="row" justifyContent="space-between"
                                alignItems="center">
                                <Grid item xs={12} sm={12} md={11} lg={11} mt={1}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} sm={12} md={12} lg={12}>
                                            <Grid container direction="row">
                                                <Grid item xs={12} sm={12} md={2.5} lg={1.6}
                                                    sx={{ display: 'flex', alignItems: 'center' }}>
                                                    <FormLabel><Typography variant="pnspsFormParagraph">
                                                        <FormattedMessage id="draftFile"/>:
                                                    </Typography></FormLabel>
                                                </Grid>
                                                <Grid item xs={12} sm={12} md={9} lg={9} >
                                                    <Grid container direction="row" alignItems="center" justifyContent="flex-start">
                                                        <Grid item xs={12} sm={12} md={12} lg={12} sx={{ wordBreak: 'break-word' , }}>
                                                            <Typography
                                                                fullWidth
                                                                id='fileName'
                                                                variant="pnspsFormParagraph"
                                                            >
                                                                {fileDetail.filename}
                                                            </Typography>
                                                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                                <Button
                                                                    sx={{ml:3}}
                                                                    variant="contained"
                                                                    onClick={onDownloadClick()}
                                                                    aria-label={intl.formatMessage({id: 'download'})}
                                                                    title={intl.formatMessage({id: 'download'})}
                                                                    color="save"
                                                                    startIcon={<DownloadIcon sx={{alignItems:"center"}}/>}
                                                                >
                                                                    <FormattedMessage id="download"/>
                                                                </Button>
                                                            </ThemeProvider>
                                                        </Grid>
                                                    </Grid>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                            {isORGLoggedIn() ?
                                <Grid item xs={12} md={9} lg={6} sx={{ mb: 1, paddingTop: 2 }}>
                                    <Grid container alignItems={"center"}>
                                        <Grid item xs={12} md={3} lg={3}
                                            sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FormLabel><Typography variant="pnspsFormParagraph">Care Of:</Typography></FormLabel>
                                        </Grid>
                                        <Grid item xs={12} md={9} lg={9}>
                                            <Typography variant="pnspsFormParagraph">{currentApplicationDetailData.careOf}</Typography>
                                        </Grid>
                                    </Grid>
                                </Grid> : null
                            }
                            <Grid item xs={12} md={9} lg={6} sx={{ mb: 1, paddingTop: 2 }}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <FormLabel><Typography variant="pnspsFormParagraph">
                                            <FormattedMessage id="extraMark"/>:
                                        </Typography></FormLabel>
                                    </Grid>
                                    <Grid item xs={12} md={9} lg={9}>
                                        <Typography variant="pnspsFormParagraph">{currentApplicationDetailData.remarks}</Typography>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                    <div>
                        <Dialog
                            open={isPopUp}
                            onClose={() => setIsPopUp(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="payConfirm"/>
                                </Typography>
                            </DialogTitle>
                            <DialogContent style={{ display: 'flex', }}>
                                <Stack direction="column" justifyContent="space-between">
                                    <Typography variant="h4">
                                        <FormattedMessage id="totalAmount"/> (HK$): {FormatUtils.currencyFormat(fee)}
                                    </Typography>
                                </Stack>
                            </DialogContent>
                            <DialogActions>
                                <Button
                                    onClick={() => setIsPopUp(false)}
                                    aria-label={intl.formatMessage({id: 'close'})}
                                >
                                    <Typography variant="pnspsFormParagraph">
                                    <FormattedMessage id="close"/>
                                </Typography></Button>
                                <Button
                                    onClick={() => doPayment()}
                                    aria-label={intl.formatMessage({id: 'confirm'})}
                                >
                                    <Typography variant="pnspsFormParagraph">
                                    <FormattedMessage id="confirm"/>
                                </Typography></Button>
                            </DialogActions>
                        </Dialog>
                    </div>
                    <div>
                        <Dialog
                            open={errorPopUp}
                            onClose={() => setErrorPopUp(false)}
                            PaperProps={{
                                sx: {
                                    minWidth: '40vw',
                                    maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                                    maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                                }
                            }}
                        >
                            <DialogTitle></DialogTitle>
                            <Typography variant="h2" style={{ padding: '16px' }}>行動失敗</Typography>
                            <DialogContent style={{ display: 'flex', }}>
                                <Stack direction="column" justifyContent="space-between">
                                    {
                                        errorText
                                    }
                                </Stack>
                            </DialogContent>
                            <DialogActions>
                                <Button
                                    onClick={() => setErrorPopUp(false)}
                                    aria-label={intl.formatMessage({id: 'close'})}
                                >
                                    <Typography variant="pnspsFormParagraph">
                                        <FormattedMessage id="close"/>
                                    </Typography></Button>
                            </DialogActions>
                        </Dialog>
                    </div>
                </form>
            </MainCard >
    );
};

export default ApplicationDetailCard;
