import {
  useEffect,
  useState,
  lazy
} from "react";

// material-ui
import {
  Grid,
  Typography,
  Stack,
  Box,
  Button
} from '@mui/material';
import Loadable from 'components/Loadable';
import {
  // useNavigate,
  useParams
} from "react-router-dom";
import axios from "axios";
import * as HttpUtils from "utils/HttpUtils";
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
const ApplicationDetailCard = Loadable(lazy(() => import('./ApplicationDetailCard')));
const GazetteDetailCard = Loadable(lazy(() => import('./GazetteDetailCard')));
const ClientDetailCard = Loadable(lazy(() => import('./ClientDetailCard')));
const TabTableDetail = Loadable(lazy(() => import('./tabTableDetail/TabTable')));
import {
  GET_PUBLIC_NOTICE_APPLY_DETAIL,
  UPDATE_PUBLIC_NOTICE_APPLY_DETAIL,
  SET_PUBLIC_NOTICE_GROUP_DETAIL,
  SET_PUBLIC_NOTICE_STATUS_NOT_ACCEPT,
  SET_PUBLIC_NOTICE_STATUS_COMPLATED,
  SET_PUBLIC_NOTICE_STATUS_WITHDRAW,
  SET_PUBLIC_NOTICE_STATUS_RESUBMIT,
  SET_PUBLIC_NOTICE_STATUS_REVIEWED,
  SET_PUBLIC_NOTICE_STATUS_PUBLISH,
  SET_PUBLIC_NOTICE_STATUS_REVOKE,
  SET_PUBLIC_NOTICE_STATUS_PAID
} from "utils/ApiPathConst";
const StatusChangeDialog = Loadable(lazy(() => import('./StatusChangeDialog')));
import * as DateUtils from "utils/DateUtils";
import { notifyActionSuccess, notifySaveSuccess } from "utils/CommonFunction";
import ForwardIcon from '@mui/icons-material/Forward';
import { useNavigate } from "react-router-dom";
import {getModeByTextEng} from "utils/statusUtils/PublicNoteStatusUtils";

// ==============================|| Body - DEFAULT ||============================== //

const PublicNoticeDetail_GLD = () => {
  const params = useParams();
  const navigate = useNavigate()
  const [applicationDetailData, setApplicationDetailData] = useState({});
  const [isLoading, setLoading] = useState(false);
  const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
  const [getUploadStatus, setUploadStatus] = useState(false);
  const [proofCount, setProofCount] = useState(0);
  const [paymentCount, setPaymentCount] = useState(0);
  const [statusHistoryCount, setStatusHistoryCount] = useState(0);

  //pageTitle
  const [appNo, setAapNo] = useState("");
  const [gazetteIssue, setGazetteIssue] = useState("");
  const [issueDate, setIssueDate] = useState("");
  const [issueNum, setIssueNum] = useState("");
  const [groupNo, setGroupNo] = useState("");
  // const [groupTitle, setGroupTitle] = useState("");
  const [mode, setMode] = useState("");

  //statusWindow
  const [open, setOpen] = useState(false);
  const [getStatus, setStatus] = useState("");
  const [statusWindowAccepted, setStatusWindowAccepted] = useState(false);
  const [statusConfirmLoading, setStatusConfirmLoading] = useState(false);
  const [selectedGazetteGroup, setSelectedGazetteGroup] = useState({});
  const [selectedGazetteGroupInputType, setSelectedGazetteGroupInputType] = useState("");
  const [getReason, setReason] = useState({});

  //editMode
  const [updateApplicationObject, setUpdateApplicationObject] = useState({});
  const [editMode, isEditMode] = useState(false);
  const [isSave, setiIsSave] = useState(false);


  const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
  }

  const title = groupNo != null ? (appNo + ", " + gazetteIssue + ", " + issueNum + " , " + groupNo +" "+ mode) : (appNo + ", " + gazetteIssue + ", " + issueNum+" "+ mode)

  useEffect(() => {
    loadApplicationDetail();
  }, []);

  // useEffect(() => {
  //   if (reload){
  //     loadApplicationDetail()
  //   }
  // }, [reload]);

  useEffect(() => {
    if (editMode && isSave) {
      onUpdateClick(updateApplicationObject)
    }
  }, [updateApplicationObject]);

  const loadApplicationDetail = () => {
    if (params.id > 0) {
      axios.get(`${GET_PUBLIC_NOTICE_APPLY_DETAIL}/${params.id}`)
        .then((response) => {
          if (response.status === 200) {
            setApplicationDetailData(response.data);
            setProofCount(response.data.proofCount);
            setPaymentCount(response.data.paymentCount);
            setStatusHistoryCount(response.data.statusHistoryCount);

            const gazetteIssueDetail = response.data.gazetteIssueDetail;
            setAapNo(response.data.data.appNo);
            setGazetteIssue(gazetteIssueDetail.issueYear + " Vol " + gazetteIssueDetail.volume);
            setIssueNum(" No. " + gazetteIssueDetail.issueNo);
            setIssueDate(DateUtils.dateFormat(gazetteIssueDetail.issueDate, "D MMM YYYY (ddd)"));
            setGroupNo(response.data.data.groupNo);
            if (response.data.data?.mode != null){
              const modeStr = getModeByTextEng(response.data.data.mode);
              setMode("("+modeStr+")");
            }
            setLoading(false);
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        });
    }
  }

  const onUpdateClick = (updateApplicationObject) => {
    const data = updateApplicationObject.objectData
    if (params.id > 0) {
      setLoading(true);
      axios.post(`${UPDATE_PUBLIC_NOTICE_APPLY_DETAIL}/${params.id}`,
        {
          contactPerson: data.contactPerson,
          contactFaxNo: data.contactFaxNo,
          contactTelNo: data.contactTelNo,
        }
      )
        .then((response) => {
          if (response.status === 200) {
            location.reload();
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        });
    }
  };

  useEffect(() => {
    // console.log(getStatus)
    if (getStatus !== "") {
      setOpen(true)
    }
  }, [getStatus]);

  const handleClose = () => {
    handleReset()
    setOpen(false);
    setStatus("")
    setStatusWindowAccepted(false)
  };

  const handleReset = () => {
    setSelectedGazetteGroupInputType("")
    setSelectedGazetteGroup({});
    setReason({});
  };

  useEffect(() => {
    if (!statusWindowAccepted) {
      setStatusConfirmLoading(false);
      return;
    }
    setStatusConfirmLoading(true);
    if (getStatus == "genGazetteCode") {
      onAcceptedClick()
    } else if (getStatus == "complete") {
      onComplatedClick()
    } else if (getStatus == "withdraw") {
      onWithdrawnClick()
    } else if (getStatus == "notAccepted") {
      onNotAcceptClick(getReason);
    } else if (getStatus == "resubmit") {
      onReSubmitClick(getReason);
    } else if (getStatus == "publish") {
      onPublishClick();
    } else if (getStatus == "revoke") {
      onRevokeClick();
    } else if(getStatus == "paid"){
      onPaidClick();
    } else {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
    }
  }, [statusWindowAccepted]);

  const onAcceptedClick = () => {
    if (params.id > 0) {
      axios.post(`${SET_PUBLIC_NOTICE_GROUP_DETAIL}/${params.id}`,
        {
          "groupTitle": selectedGazetteGroup.title,
          "groupNo": selectedGazetteGroup.type,
        }
      )
        .then((response) => {
          if (response.status === 204) {
            setOpen(false);
            handleClose();
            // location.reload();
            loadApplicationDetail()
            notifyActionSuccess("Gen Gazette Code Success!")
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        })
        .finally(() => {
          setStatusConfirmLoading(false);
          setStatusWindowAccepted(false);
        });
    } else {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
    }
  };

  const onNotAcceptClick = (reason) => {
    if (params.id <= 0) {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
      return;
    }
    HttpUtils.post({
      url: `${SET_PUBLIC_NOTICE_STATUS_NOT_ACCEPT}/${params.id}`,
      params: reason,
      onSuccess: function () {
        setOpen(false);
        handleClose();
        // location.reload();
        loadApplicationDetail()
        notifySaveSuccess()
      },
      onFail: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      },
      onError: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      }
    });
  }

  const onPublishClick = () => {
    if (params.id <= 0) {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
      return;
    }
    HttpUtils.get({
      url: `${SET_PUBLIC_NOTICE_STATUS_PUBLISH}/${params.id}`,
      onSuccess: function () {
        setOpen(false);
        handleClose();
        loadApplicationDetail()
        notifySaveSuccess()
      },
      onFail: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      },
      onError: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      },
      onFinally: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      }
    });
  }

  const onPaidClick = () => {
    if (params.id > 0) {
      axios.get(`${SET_PUBLIC_NOTICE_STATUS_PAID}/${params.id}`)
        .then((response) => {
          if (response.status === 204) {
            setOpen(false);
            handleClose();
            // location.reload();
            loadApplicationDetail()
            notifySaveSuccess()
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        })
        .finally(() => {
          setStatusConfirmLoading(false);
          setStatusWindowAccepted(false);
        });
    } else {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
    }
  };

  const onComplatedClick = () => {
    if (params.id > 0) {
      axios.get(`${SET_PUBLIC_NOTICE_STATUS_COMPLATED}/${params.id}`)
        .then((response) => {
          if (response.status === 204) {
            setOpen(false);
            handleClose();
            // location.reload();
            loadApplicationDetail()
            notifySaveSuccess()
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        })
        .finally(() => {
          setStatusConfirmLoading(false);
          setStatusWindowAccepted(false);
        });
    } else {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
    }
  };

  const onWithdrawnClick = () => {
    if (params.id > 0) {
      axios.get(`${SET_PUBLIC_NOTICE_STATUS_WITHDRAW}/${params.id}`)
        .then((response) => {
          if (response.status === 204) {
            setOpen(false);
            handleClose();
            loadApplicationDetail()
            notifyActionSuccess("Withdrawn Success!")
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        })
        .finally(() => {
          setStatusConfirmLoading(false);
          setStatusWindowAccepted(false);
        });
    } else {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
    }
  };

  const onReSubmitClick = (reason) => {
    if (params.id > 0) {
      HttpUtils.post({
        url: `${SET_PUBLIC_NOTICE_STATUS_RESUBMIT}/${params.id}`,
        params: reason,
        onSuccess: function () {
          setOpen(false);
          handleClose();
          // location.reload();
          loadApplicationDetail()
          notifySaveSuccess()
        },
        onFail: () => {
          setStatusConfirmLoading(false);
          setStatusWindowAccepted(false);
        },
        onError: () => {
          setStatusConfirmLoading(false);
          setStatusWindowAccepted(false);
        }
      });
      // axios.post(`${SET_PUBLIC_NOTICE_STATUS_RESUBMIT}/${params.id}`)
      //   .then((response) => {
      //     if (response.status === 204) {
      //       setOpen(false);
      //       handleClose();
      //       // location.reload();
      //       loadApplicationDetail()
      //       notifySaveSuccess()
      //     }
      //   })
      //   .catch(error => {
      //     console.log(error);
      //     return false;
      //   });
    } else {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
    }
  };

  const onRevokeClick = () => {
    if (params.id <= 0) {
      setStatusConfirmLoading(false);
      setStatusWindowAccepted(false);
      return;
    }
    HttpUtils.get({
      url: `${SET_PUBLIC_NOTICE_STATUS_REVOKE}/${params.id}`,
      onSuccess: function () {
        setOpen(false);
        handleClose();
        loadApplicationDetail()
        notifySaveSuccess()
      },
      onFail: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      },
      onError: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      },
      onFinally: () => {
        setStatusConfirmLoading(false);
        setStatusWindowAccepted(false);
      }
    });
  }

  useEffect(() => {
    const status = applicationDetailData.data != undefined ? applicationDetailData.data.status : ""
    if (status === "submitted" && params.id > 0 && getUploadStatus) {
      axios.get(`${SET_PUBLIC_NOTICE_STATUS_REVIEWED}/${params.id}`)
        .then((response) => {
          if (response.status === 204) {
            setUploadStatus(false);
            location.reload();
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        });
    } else {
      setUploadStatus(false);
    }
  }, [getUploadStatus]);

  return (
    <Grid container sx={{ width: "100%", backgroundColor: 'backgroundColor.default' }} direction="column">
      <StatusChangeDialog open={open}
        handleClose={handleClose}
        setReason={setReason}
        setStatusWindowAccepted={setStatusWindowAccepted}
        getStatus={getStatus}
        issueDate={issueDate}
        issueNum={issueNum}
        gazetteIssue={gazetteIssue}
        confirmLoading={statusConfirmLoading}
        //combo value
        selectedGazetteGroup={selectedGazetteGroup}
        setSelectedGazetteGroup={setSelectedGazetteGroup}
        selectedGazetteGroupInputType={selectedGazetteGroupInputType}
        setSelectedGazetteGroupInputType={setSelectedGazetteGroupInputType}
      />
      <Grid item xs={12} >
        <div style={BackgroundHead}>
          <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
            <Typography ml={15} color='#FFF' variant="h4">Application</Typography>
          </Stack>
        </div>
      </Grid>
      <Grid item xs={12} sm={12} md={12} lg={12}>
        <Stack direction="row">
          <Button title="Back" sx={{ ml: 3.5, mt: 2.5 }} style={{ border: '2px solid' }} variant="outlined" onClick={() => { navigate(-1) }}>
            <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
          </Button>
          <Typography ml={4} mt={3} variant="h4">{title}</Typography>
        </Stack>
      </Grid>
      {/* <Grid item xs={12} >
        <Stack direction="row" height='20px' justifyContent="flex-start" alignItems="center">
          <Typography ml={4} mt={3} variant="h4">{title}</Typography>
        </Stack>
      </Grid> */}
      <Grid item xs={12} sm={12} md={12} lg={12} xl={12} >
        <Grid container direction="row">
          <Grid item xs={12} md={12} lg={9} xl={9}>
            <Grid container direction="column">
              <Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
                <Box xs={12} sx={{ ml: 2, mt: 3, mr: { xs: 2, sm: 2 }, borderRadius: '10px', backgroundColor: '#ffffff' }}>
                  {isLoading && editMode ?
                    <LoadingComponent /> :
                    <ApplicationDetailCard
                      applicationDetailData={applicationDetailData}
                      setStatus={setStatus}
                      // setReload = {setReload}
                      setUploadStatus={setUploadStatus}
                      setUpdateApplicationObject={setUpdateApplicationObject}
                      isEditMode={isEditMode}
                      setiIsSave={setiIsSave}
                      statusDialogOpen={open}
                      statusDialogKind={getStatus}
                      statusActionLoading={statusConfirmLoading}
                    // isNewRecord={isNewRecord}
                    />
                  }
                </Box>
              </Grid>
              <Grid item xs={12} md={12} lg={12} xl={12}>
                <Box xs={12} sx={{ ml: 2, mt: 3, mr: { xs: 2, sm: 2 }, borderRadius: '10px', backgroundColor: '#ffffff' }}>
                  <GazetteDetailCard
                    // updateUserObject={updateUserObject}
                    applicationDetailData={applicationDetailData}
                    setStatus={setStatus}
                  // isCollectData={isCollectData}
                  // isNewRecord={isNewRecord}
                  />
                </Box>
              </Grid>
              <Grid item xs={12} md={12} lg={12} xl={12}>
                <Box xs={12} sx={{ ml: 2, mt: 3, mr: { sm: 2 }, borderRadius: '10px', width: { xs: '92vw', sm: '96.5vw', md: "auto" }, backgroundColor: '#ffffff' }}>
                  <TabTableDetail
                    appId={params.id}
                    proofCount={proofCount}
                    paymentCount={paymentCount}
                    statusHistoryCount={statusHistoryCount}
                    setProofCount = {setProofCount}
                    setPaymentCount = {setPaymentCount}
                    setStatusHistoryCount = {setStatusHistoryCount}
                  />
                </Box>
                <br />
              </Grid>
            </Grid>
          </Grid>
          <Grid item xs={12} md={12} lg={3} xl={3} sx={{ mt: { xs: -3, sm: -3 } }}>
            <Grid container>
              <Grid item xs={12} md={12}>
                <Box xs={12} md={12} sx={{ ml: 2, mt: 3, mb: 3, mr: { xs: 2, sm: 2 }, borderRadius: '10px', backgroundColor: '#ffffff' }}>
                  <ClientDetailCard
                    // updateUserObject={updateUserObject}
                    applicationDetailData={applicationDetailData}
                  // isCollectData={isCollectData}
                  // isNewRecord={isNewRecord}
                  />
                </Box>
              </Grid>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};

export default PublicNoticeDetail_GLD;
