import React, {
  useEffect,
  useState,
  useRef,
  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 titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
const ApplicationDetailCard = Loadable(lazy(() => import('./ApplicationDetailCard')));
const StatusChangeDialog = Loadable(lazy(() => import('./StatusChangeDialog')));
const TabTableDetail = Loadable(lazy(() => import('./tabTableDetail/TabTable')));
import {
  GET_PUBLIC_NOTICE_APPLY_DETAIL,
  SET_PUBLIC_NOTICE_STATUS_CANCELLED
} from "utils/ApiPathConst";
import { useNavigate } from "react-router-dom";

import ForwardIcon from '@mui/icons-material/Forward';
import { notifyActionSuccess } from "utils/CommonFunction";
import { FormattedMessage, useIntl } from "react-intl";
import usePageTitle from "components/usePageTitle";
// ==============================|| Body - DEFAULT ||============================== //

const DashboardDefault = () => {
  usePageTitle("myPublicNotice");
  
  const params = useParams();
  const [applicationDetailData, setApplicationDetailData] = useState({});
  const [appNo, setAapNo] = useState("");
  const [gazetteIssue, setGazetteIssue] = useState("");
  const [issueNum, setIssueNum] = useState("");
  const navigate = useNavigate()
  const intl = useIntl();
  //statusWindow
  const [open, setOpen] = useState(false);
  const [getStatus, setStatus] = useState("");
  const [statusWindowAccepted, setStatusWindowAccepted] = useState(false);
  const [cancelLoading, setCancelLoading] = useState(false);
  const cancellingRef = useRef(false);

  const [proofCount, setProofCount] = useState(0);
  const [paymentCount, setPaymentCount] = useState(0);
  const [fee, setFee] = useState(0);

  const title = appNo + ", " + gazetteIssue + ", " + issueNum

  const _sx = {
    boxShadow: 1,
    border: 1,
    borderColor: '#DDD',
    '& .MuiDataGrid-cell': {
      borderTop: 1,
      borderBottom: 1,
      borderColor: "#EEE"
    },
    '& .MuiDataGrid-footerContainer': {
      border: 1,
      borderColor: "#EEE"
    }
  }

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

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

  const loadApplicationDetail = () => {
    if (params.id > 0) {
      axios.get(`${GET_PUBLIC_NOTICE_APPLY_DETAIL}/${params.id}`)
        .then((response) => {
          if (response.status === 200) {
            setApplicationDetailData(response.data);
            const gazetteIssueDetail = response.data.gazetteIssueDetail;
            setAapNo(response.data.data.appNo);
            setGazetteIssue(gazetteIssueDetail.issueYear + " Vol " + gazetteIssueDetail.volume);
            setIssueNum(" No. " + gazetteIssueDetail.issueNo);

            setProofCount(response.data.proofCount);
            setPaymentCount(response.data.paymentCount);
            setFee(response.data.fee);
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        });
    }
  }

  useEffect(() => {
    if (applicationDetailData.data === null) {
      navigate('/publicNotice');
    }
  }, [applicationDetailData]);

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

  useEffect(() => {
    if (statusWindowAccepted) {
      if (getStatus == "cancel") {
        onCancelledClick()
      }
    }
  }, [statusWindowAccepted]);

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

  const onCancelledClick = () => {
    if (cancellingRef.current) return;
    if (params.id > 0) {
      cancellingRef.current = true;
      setCancelLoading(true);
      axios.get(`${SET_PUBLIC_NOTICE_STATUS_CANCELLED}/${params.id}`)
        .then((response) => {
          if (response.status === 204) {
            notifyActionSuccess("取消成功!")
            setOpen(false);
            handleClose();
            loadApplicationDetail()
            window.location.reload();
          }
        })
        .catch(error => {
          console.log(error);
          return false;
        })
        .finally(() => {
          cancellingRef.current = false;
          setCancelLoading(false);
        });
    }
  };

  return (
    <Grid container sx={{ backgroundColor: '#ffffff' }} direction="column">
      <StatusChangeDialog
        open={open}
        handleClose={handleClose}
        setStatusWindowAccepted={setStatusWindowAccepted}
        getStatus={getStatus}
        confirmLoading={cancelLoading}
      />
      <Grid item xs={12}>
        <div style={BackgroundHead}>
          <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
            <Typography component="h1" ml={15} color='#FFF' variant="h4" sx={{ display: { xs: 'none', sm: 'none', md: 'block' } }}>
              <FormattedMessage id="myPublicNotice" />
            </Typography>
          </Stack>
        </div>
      </Grid>
      <Grid item xs={12} md={12}>
        <Grid container direction="column" justifyContent="flex-start" alignItems="center">
          <Grid item xs={12} width={{ xs: "90%", sm: "90%", md: "60%", lg: "60%" }}>
            <Stack direction="row">
              <Button
                aria-label={intl.formatMessage({ id: 'back' })}
                title={intl.formatMessage({ id: 'back' })}
                sx={{ ml: 0, mt: 2.5 }} style={{ border: '2px solid' }}
                variant="outlined" onClick={() => { navigate("/publicNotice") }}
              >
                <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
              </Button>
              <Typography component="h2" ml={3} mt={3} variant="h4">{title}</Typography>
            </Stack>
          </Grid>
          <Grid item width={{ md: "60%", xs: "90%" }}>
            <Box xs={12} mt={3} sx={{ border: '0px groove grey', borderRadius: '10px', ..._sx }}>
              <ApplicationDetailCard
                setStatus={setStatus}
                applicationDetailData={applicationDetailData}
                fee={fee}
              />
            </Box>
          </Grid>
          <Grid item width={{ md: "75%" }}>
            <Box xs={12} mt={3} sx={{ border: '0px groove grey', borderRadius: '10px', ..._sx, mb: 2 }}>
              <TabTableDetail
                appId={params.id}
                proofCount={proofCount}
                paymentCount={paymentCount}
                setProofCount={setProofCount}
                setPaymentCount={setPaymentCount}
              />
            </Box>
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};

export default DashboardDefault;
