// material-ui
import {
    Grid,
    Typography,
    Stack,
    Box,
    Button
} from '@mui/material';
import * as UrlUtils from "utils/ApiPathConst";
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as DateUtils from "utils/DateUtils";
import * as FormatUtils from "utils/FormatUtils"
import { useParams } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import ForwardIcon from '@mui/icons-material/Forward';

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
const ApplicationDetails = Loadable(React.lazy(() => import('./ApplicationDetails')));
const ProofForm = Loadable(React.lazy(() => import('./ProofForm')));
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}

// ==============================|| DASHBOARD - DEFAULT ||============================== //

const Index = () => {
    const params = useParams();
    const navigate = useNavigate()

    const [record, setRecord] = React.useState({});
    const [onReady, setOnReady] = React.useState(false);
    const [isOverTime, setIsOverTime] = React.useState(false);
    const [showCancelBtn, setShowCancelBtn] = React.useState(false);
    const [showProofBtn, setShowProofBtn] = React.useState(false);

    React.useLayoutEffect(() => {
        loadForm();
    }, []);

    React.useLayoutEffect(() => {
        setOnReady(true);
    }, [record]);


    const loadForm = () => {
        if (params.id > 0) {

            HttpUtils.get({
                url: UrlUtils.GET_PROOF + "/" + params.id,
                onSuccess: (responseData) => {
                    if (!responseData.data?.id) {
                        navigate("/proof/search");
                    }
                    setShowProofBtn(responseData.data.action != null && responseData.data.action === true);
                    responseData.data["phoneNumber"] = JSON.parse(responseData.data.contactTelNo).phoneNumber;
                    responseData.data["tel_countryCode"] = JSON.parse(responseData.data.contactTelNo).countryCode;

                    responseData.data["faxNumber"] = JSON.parse(responseData.data.contactFaxNo).faxNumber;
                    responseData.data["fax_countryCode"] = JSON.parse(responseData.data.contactFaxNo).countryCode;

                    responseData.data["issueNoStr"] = responseData.data.issueYear
                        + " Vol. " + FormatUtils.zeroPad(responseData.data.issueVolume, 3)
                        + ", No. " + FormatUtils.zeroPad(responseData.data.issueNo, 2);

                    responseData.data["issueDateStr"] = DateUtils.dateFormat(responseData.data.issueDate, "D MMM YYYY (ddd)");

                    responseData.data["groupType"] = responseData.data.groupTitle;
                    responseData.data["action"] = responseData.data.replyDate ? responseData.data.action : true;

                    let proofPaymentDeadline = DateUtils.convertToDate(responseData.data.proofPaymentDeadline);
                    let current = new Date();
                    setIsOverTime(current.getTime() > proofPaymentDeadline.getTime());
                    setShowCancelBtn(responseData.data.cancelled || responseData.data.replyDate || current.getTime() > proofPaymentDeadline.getTime())



                    setRecord(responseData.data);
                }
            });
        }
    }

    // calculate back button position

    // const applicationDetailsRef = React.useCallback(node => {
    //     if (node === null) {
    //         return
    //     } else {
    //         setBackButtonLeftPos(`${node.getBoundingClientRect()?.left}px`)
    //     }
    // })

    // const [backButtonPos, setBackButtonPos] = React.useState()
    // const backButtonRef = React.useRef()
    // React.useLayoutEffect(()=>{
    // console.log(applicationDetailsRef.current?.getBoundingClientRect())
    //     if (backButtonRef.current) backButtonRef.current.style.marginLeft = `${backButtonPos}`
    // },[backButtonPos])

    // React.useEffect(()=>{
    //     if (backButtonRef.current) backButtonRef.current.style.marginLeft = `${backButtonLeftPos}`
    // }, [backButtonLeftPos])

    return (
        !onReady ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            (
                <Grid container sx={{ minHeight: '110vh', backgroundColor: 'backgroundColor.default' }} direction="column" justifyContent="flex-start" alignItems="center" >
                    <Grid item xs={12} width="100%">
                        <div style={BackgroundHead} width="100%">
                            <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                                <Typography ml={15} color='#FFF' variant="h4">Proof Record</Typography>
                            </Stack>
                        </div>
                    </Grid>
                    <Grid item xs={12} width="100%">
                        <Button title="Back" sx={{ ml: 6, mt: 2.5 }} style={{ border: '2px solid' }} variant="outlined" onClick={() => { navigate("/proof/search") }}>
                            <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                        </Button>
                    </Grid>
                    {/*row 1*/}
                    <Grid item xs={12} md={12} >
                        <Grid container justifyContent="flex-start" alignItems="center" direction="column">
                            <center>
                                <Grid item xs={12} md={12} sx={{ pt: 2, ml: 6, mr: 6, }}>
                                    <Box xs={12} md={12} sx={{ p: 4, borderRadius: '10px', backgroundColor: '#ffffff' }}>
                                        <ApplicationDetails
                                            // setBackButtonPos={setBackButtonPos}
                                            formData={record}
                                            showCancelBtn={showCancelBtn}
                                            showProofBtn={showProofBtn}
                                            style={{
                                                display: "flex",
                                                height: "100%",
                                                flex: 1
                                            }}
                                        />
                                    </Box>
                                </Grid>
                                <Grid item xs={12} md={12} sx={{ pt: 3, pb: 2, ml: 6, mr: 6, }}>
                                    <Box xs={12} md={12} sx={{ p: 4, borderRadius: '10px', backgroundColor: '#ffffff' }}>
                                        <ProofForm
                                            formData={record}
                                            isOverTime={isOverTime}
                                        />
                                    </Box>
                                </Grid>
                            </center>
                        </Grid>
                    </Grid>
                    {/*row 2*/}
                </Grid >


            )


    );
};

export default Index;
