import { useState } from 'react';

// material-ui
import {
  Grid,
  Typography,
  Stack,
  Button,
  Box,
  Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import { isORGLoggedIn, } from "utils/Utils";
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import { FormattedMessage, useIntl } from "react-intl";
import AdsClickRoundedIcon from '@mui/icons-material/AdsClickRounded';
import * as React from "react";
import Loadable from 'components/Loadable';
import * as HttpUtils from "utils/HttpUtils";
import * as UrlUtils from "utils/ApiPathConst";
import * as DateUtils from "utils/DateUtils";
import { checkPaymentSuspension } from "utils/Utils";

const Message = Loadable(React.lazy(() => import('./Message')));
const Notice = Loadable(React.lazy(() => import('./Notice')));
// import { lazy } from 'react';

const LoadingComponent = Loadable(React.lazy(() => import('../../extra-pages/LoadingComponent')));

import { useNavigate } from "react-router-dom";
import usePageTitle from "components/usePageTitle";

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

const DashboardDefault = () => {
  usePageTitle("Dashboard");
  const navigate = useNavigate()
  const intl = useIntl();
  const userData = JSON.parse(localStorage.getItem("userData"));
  const BackgroundHead = {
    // backgroundColor: '#0d47a1',
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
  }

  const { locale } = intl;
  const [messageOnReady, setMessageOnReady] = useState(false);
  const [onNoticeReady, setNoticeOnReady] = useState(false);
  const [isLoading, setLoding] = useState(true);
  const [itemList, setItemList] = React.useState([]);
  const [listData, setListData] = React.useState([]);
  const [isPopUp, setIsPopUp] = React.useState(false);
  
  React.useEffect(() => {
    loadMessageData()
    loadNoticeData()
    
    localStorage.setItem('searchCriteria',"")
  }, []);

  const getWelcomeMsg=()=>{
    
    var current = new Date()
    var curHr = current.getHours()

    if (curHr < 12) {
      return <FormattedMessage id="welcomeMsg_am" />
    } else if (curHr < 18) {
      return <FormattedMessage id="welcomeMsg_pm" />
    } else {
      return <FormattedMessage id="welcomeMsg_night" />
    }
  }

  React.useEffect(() => {
    // console.log(messageOnReady)
    // console.log(onNoticeReady)
    if(messageOnReady&&onNoticeReady){
      setLoding(false)
      if(checkPaymentSuspension()){
        setIsPopUp(true);
      }
      // console.log(123)
    }
  }, [messageOnReady,onNoticeReady]);

  const loadMessageData = () => {
    HttpUtils.get({
        url: UrlUtils.GET_MSG_DASHBOARD,
        onSuccess: function (response) {
            const list = response.map((item) => (
                    <Button
                      key={item.id}
                      onClick={() => navigate("/msg/details/" + item.id)}
                      sx={{
                        p: 2,
                        justifyContent: "flex-start",
                        textTransform: "none",
                        fontSize: "inherit",
                        fontWeight: "inherit",

                        // text always readable
                        color: "#1A1A1A",

                        // unread gets subtle highlight
                        backgroundColor: item.readTime ? "transparent" : "#F5F7FA",

                        "&:hover": {
                          backgroundColor: "#EEF2F7",
                        },
                      }}
                    >
                        <Stack direction="column">
                            <Typography
                              component="h3"
                              variant="h6"
                              align="justify"
                              sx={(theme) => ({
                                ...theme.typography.h6,
                                fontWeight: item.readTime ? 400 : 600,
                              })}
                            >
                              {item.subject}
                            </Typography>
                            <Typography component="span" variant="subtitle2" sx={{ color: '#000' }} align="justify">
                              {DateUtils.datetimeStr(item.sentDate)}
                            </Typography>
                        </Stack>
                    </Button>
            ));

            setItemList(list);
            setMessageOnReady(true);
            // console.log('123')
        },
        onError: function (){
            // console.log('123')
            setMessageOnReady(true);
        }
    });
    // props.setMessageOnReady(true);

  };

  const loadNoticeData = () => {
    HttpUtils.get({
        url: UrlUtils.GET_ANNOUNCE_DASHBOARD,
        onSuccess: function (response) {
            setListData(response);
            setNoticeOnReady(true)
        },
        onError: function () {
            setNoticeOnReady(true)
        }
    });
  };

  return (
        isLoading ?
          <Grid container sx={{ minHeight: '87vh' }} direction="column">
            <Grid item xs={12} >
              <div style={BackgroundHead}>
                <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                  {/* <Typography variant="h5">我的公共啟事</Typography> */}
                  <Typography component="h1" color='#FFF' variant="h5" sx={{ ml: 10, display: { xs: 'none', sm: 'none', md: 'block' } }}>
                    {isORGLoggedIn() ? userData.fullenName: (locale === 'en' ?userData.fullenName: userData.fullchName)}, {getWelcomeMsg()}
                  </Typography>
                </Stack>
              </div>
            </Grid>
            <Grid item xs={12} md={12} sx={{ textAlign: "center" }}>
              <Grid container sx={{ minHeight: '75vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        :
        <Grid container sx={{ minHeight: '87vh' }} direction="column">
          <Grid item xs={12} >
            <div style={BackgroundHead}>
              <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                {/* <Typography variant="h5">我的公共啟事</Typography> */}
                <Typography component="h1" color='#FFF' variant="h5" sx={{ ml: 10, display: { xs: 'none', sm: 'none', md: 'block' } }}>
                  {isORGLoggedIn() ? userData.fullenName: (locale === 'en' ?userData.fullenName: userData.fullchName)}, {getWelcomeMsg()}
                </Typography>
              </Stack>
            </div>
          </Grid>
          <Grid item xs={12} md={12} sx={{ textAlign: "center" }}>
            <Grid container justifyContent="center" spacing={2} sx={{ pt: 2 }} alignitems="stretch" >
              <Grid item xs={12} lg={5} sx={{ pt: 2 }} style={{ height: '100%' }}>
                <Button
                  xs={12}
                  onClick={() => { navigate("/publicNotice/apply"); }}
                  aria-label={intl.formatMessage({ id: 'submitApplication' })}
                  sx={{
                    width: "100%",
                    p: 4,
                    justifyContent: "flex-start",
                    backgroundColor: "#e1edfc",
                    border: "0px solid #0c489e",   // DARKER border (3:1+)
                    borderRadius: "10px",
                    color: "#1565C0",              // icon + default text color
                    "&:hover": {
                      backgroundColor: "#d6e6fb"
                    }
                  }}
                >
                  <Stack direction="row" spacing={2}>
                    <AdsClickRoundedIcon />
                    <Stack direction="column" alignItems="flex-start">
                      <Typography component="h2" variant="h4" sx={{ color: "#1565C0" }}>
                        <FormattedMessage id="submitApplication" />
                      </Typography>
                      <Typography sx={{ color: "#1A1A1A" }}>
                        <FormattedMessage id="applicationSubheading" />
                      </Typography>
                    </Stack>
                  </Stack>
                </Button>
                <Stack direction="row" justifyContent="space-between" sx={{ pl: 2, pr: 2, pt: 2 }} >
                  <Typography component="h2" variant="h4">
                    <FormattedMessage id="announcement" />
                  </Typography>
                  <Button
                    variant="text"
                    aria-label={intl.formatMessage({ id: 'viewAllAnnouncement' })}
                    onClick={() => { navigate("/announcement/search"); }}
                    sx={{
                      color: '#1565C0',
                      textTransform: 'none',
                      textDecoration: 'underline',
                      '&:hover': { textDecoration: 'underline' }
                    }}
                  ><u>
                      <FormattedMessage id="viewAllAnnouncement" />
                    </u></Button>
                </Stack>
                <Box xs={12} md={12} sx={{ p: 1, border: '3px solid #eee', borderRadius: '10px' }} >
                  <Notice
                    listData = {listData}
                  />
                </Box>
              </Grid>
              <Grid item xs={12} lg={5} sx={{ pt: 2 }} style={{ height: '100%' }}>
                <Stack direction="row" justifyContent="space-between" sx={{ pl: 2, pr: 2, pt: 2 }} >
<Typography component="h2" variant="h4">
                  <FormattedMessage id="systemMessage" />
                  </Typography>
                  <Button
                    variant="text"
                    aria-label={intl.formatMessage({ id: 'viewAllSystemMessage' })}
                    onClick={() => { navigate("/msg/search"); }}
                    sx={{
                      color: '#1565C0',
                      textTransform: 'none',
                      textDecoration: 'underline',
                      '&:hover': {
                        textDecoration: 'underline',
                      },
                    }}
                  ><u>
                      <FormattedMessage id="viewAllSystemMessage" />
                    </u></Button>
                </Stack>
                <Box xs={12} md={12} sx={{ p: 1, border: '3px solid #eee', borderRadius: '10px' }} >
                  <Message 
                    itemList = {itemList}
                  />
                </Box>
              </Grid>
            </Grid>
          </Grid>
          <div>
            <Dialog
                open={isPopUp}
                onClose={() => setIsPopUp(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="h5">
                  <FormattedMessage id="systemNotice" />
                </Typography>
              </DialogTitle>
              <DialogContent style={{ color: '#B00020', display: 'flex', }}>
                  <Typography variant="h5" style={{ padding: '16px' }}>
                    <div dangerouslySetInnerHTML={{ __html: intl.formatMessage({ id: "suspensionMessageText" }) }} />
                  </Typography>
              </DialogContent>
              <DialogActions>
                  <Button variant="contained" color="error" onClick={() => setIsPopUp(false)}><Typography variant="h5"><FormattedMessage id="close" /></Typography></Button>
              </DialogActions>
            </Dialog>
        </div>
        </Grid>
  );
};

export default DashboardDefault;
