import MenuIcon from '@mui/icons-material/Menu';
import { LoadingButton } from '@mui/lab';
import {
  Box,
  Divider,
  Grid,
  IconButton,
  Typography,
  useMediaQuery,
} from '@mui/material';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Outlet } from 'react-router-dom';
import notAvailableForNow from '../../assets/images/icon/waiting.svg';
import { calculateDaysLeft } from '../../utils/calculateDaysLeft';
import UpgradeYourPlan from '../../views/GlobalPopups/UpgradeYourPlan';
import CustomModal from '../../views/Modal/Modal';
import { hideAndShowFunctionality } from '../../views/Signup/signupAction';
import Header from './components/Header';
import Sidebar from './components/Sidebar';
import { useStyles } from './mainLayoutStyles';

function MainLayout() {
  const classes = useStyles();
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [alertInfo, setAlertInfo] = useState({ message: '', show: false });
  const dispatch = useDispatch();

  const hideFeature = useSelector((state) => state?.signup?.hideFeatures);

  const planDetails = useSelector((state) => state?.login?.user?.account);
  const availableJobPostings = useSelector(
    (state) => state?.login?.user?.account?.maxJobPostings
  );

  const planDaysLeft = planDetails
    ? calculateDaysLeft(planDetails.endTime)
    : 'N/A';
  const totalPlanDays = useSelector(
    (state) => state?.login?.user?.lastPurchasedPlan?.plan?.validityInDays
  );

  const isBelowMD = useMediaQuery((theme) => theme.breakpoints.down('md'));
  useEffect(() => {
    setSidebarOpen(!isBelowMD);
  }, [isBelowMD]);

  useEffect(() => {
    // Condition 1: Plan expiring in 10 days
    if (planDaysLeft <= totalPlanDays * 0.1) {
      setAlertInfo({
        message: `Your current plan is about to reach its expiration date. To continue
            to enjoy BSmart update your plan.`,
        show: true,
      });
    } else {
      setAlertInfo({ message: '', show: false });
    }
  }, [
    planDaysLeft,
    totalPlanDays,
    availableJobPostings,
  ]);

  const toggleSidebar = () => setSidebarOpen((prev) => !prev);

  const handleHideFeatures = () => {
    dispatch(hideAndShowFunctionality({ hideFeatures: false }));
  };

  return (
    <>
      {/* {<UpgradeYourPlan />} */}
      <UpgradeYourPlan message={alertInfo.message} show={alertInfo.show} />
      <Grid container spacing={0} className={classes.root}>
        {sidebarOpen && (
          <Grid item xs={12} md={2.2} className={classes.sidebar}>
            <Sidebar onClose={toggleSidebar} showCloseIcon={isBelowMD} />
          </Grid>
        )}

        <Grid
          item
          xs={12}
          md={sidebarOpen ? 9.7 : 12}
          className={classes.headerAndMainContentBox}
        >
          <Box>
            <Box className={isBelowMD ? classes.headerMobile : classes.header}>
              <Header />
              {isBelowMD && (
                <IconButton
                  onClick={toggleSidebar}
                  className={classes.menuButton}
                  size="large"
                  aria-label={sidebarOpen ? 'close menu' : 'open menu'}
                >
                  <MenuIcon />
                </IconButton>
              )}
            </Box>

            <Divider className={classes.divider} />

            <Box
              flexGrow={1}
              className={
                isBelowMD ? classes.contentBoxMobile : classes.contentBox
              }
            >
              <Box className={classes.mainContent}>
                <Outlet />
              </Box>
            </Box>
          </Box>
        </Grid>
      </Grid>
      {hideFeature && (
        <CustomModal
          onClose={handleHideFeatures}
          showFooter={false}
          showCloseButton={false}
          hideTitle={true}
          modalBodyFunction={() => (
            <Box className={classes.functionalityNotAvailablePopupBox}>
              <Box>
                <img
                  src={notAvailableForNow}
                  alt="wait for functionality"
                  className={classes.functionalityNotAvailableImage}
                />
              </Box>
              <Typography
                className={classes.functionalityNotAvailableTextBold}
                variant="h1"
              >
                Note!
              </Typography>

              <Typography
                className={classes.functionalityNotAvailableText}
                variant="h4"
              >
                This section will accessible after approval
              </Typography>
              <LoadingButton
                variant="contained"
                className={classes.functionalityNotAvailableButton}
                onClick={handleHideFeatures}
                type="submit"
              >
                <span className={classes.rightButtonText}>Okay</span>
              </LoadingButton>
            </Box>
          )}
        />
      )}
    </>
  );
}

export default MainLayout;
