import React, { useEffect, useRef, useState } from 'react';

// material-ui
import {
  Box,
  ClickAwayListener,
  Divider,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Paper,
  Popper,
} from '@mui/material';
import { useTheme } from '@mui/material/styles';

// assets
import signoutImg from '../../../assets/images/icon/signout.svg';
import phoneImg from '../../../assets/images/icon/phone.svg';

import { useStyles } from '../mainLayoutStyles';
import MainCard from './MainCard';
import Transitions from './Transitions';
import { useNavigate } from 'react-router-dom';
import { commonLogoutFunc } from '../../../utils/share';
import defaultProfilePicture from '../../../assets/images/icon/defaultProfileIcon.svg';
import { useSelector } from 'react-redux';

// ==============================|| PROFILE MENU ||============================== //

const ProfileSection = () => {
  const classes = useStyles();
  const theme = useTheme();
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);
  const [showPopup, setShowPopup] = useState(false);
  // const [showTransactionHistoryPopup, setShowTransactionHistoryPopup] =
    useState(false);
  const anchorRef = useRef(null);

  const user = useSelector((state) => state?.login?.user);
  const isSuperAdmin = user?.isSuperAdmin;

  const companyStatus = useSelector(
    (state) => state?.login?.user?.company?.status
  );

  const handleClose = (event) => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return;
    }
    setOpen(false);
  };

  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen);
  };

  useEffect(() => {
    const prevOpen = open;
    return () => {
      if (prevOpen && !open) {
        anchorRef.current.focus();
      }
    };
  }, [open]);

  const menuItems = [

    { id: 1, img: phoneImg, text: 'Contact Us', alt: 'contactUsImg' },
    { id: 2, img: signoutImg, text: 'Sign Out', alt: 'signoutImg' },
  ].filter(Boolean);

  const renderProfile = (item, index) => (
    <React.Fragment key={`profile-item-${item.id}`}>
      {
        <>
          <ListItem button key={`menu-item-${item.id}`} onClick={() => handleMenuItemClick(item)}>
            <Box className={classes.listIcon}>
              <img
                style={{ width: "20px", height: "20px" }}
                src={item.img}
                className={classes.iconImage}
                alt={item.alt}
              />
            </Box>
            <ListItemText className={classes.listText} primary={item.text} />
          </ListItem>
          {index === menuItems.length - 2 && (
            <Divider component="li" key={`divider-${item.id}`} className={classes.dividerDiv} />
          )}
        </>
      }
    </React.Fragment>
  );

  const handleMenuItemClick = (item) => {
    switch (item.id) {
      case 1:
        // navigate('/contact-us');
        break;
      case 2:
        commonLogoutFunc();
        break;
      case 3:
        // setShowTransactionHistoryPopup(true);
        break;
      case 4:
        setShowPopup(true);
        break;
      case 5:
        commonLogoutFunc();
        break;
      default:
        break;
    }
    setOpen(false);
  };

  // const handleTransactionHistoryPopupClose = () => {
  //   setShowTransactionHistoryPopup(false);
  // };
  return (
    <>
      <Box
        className={classes.profileSection}
        ref={anchorRef}
        aria-controls={open ? 'menu-list-grow' : undefined}
        onClick={handleToggle}
        aria-haspopup="true"
      >
        <img
          src={user?.profilePhoto ? user?.profilePhoto : defaultProfilePicture}
          className={classes.profileIcon}
          alt="userAvatar"
        />
        <div className={classes.onlineDot}></div>
      </Box>
      <Popper
        placement="bottom-end"
        open={open}
        anchorEl={anchorRef.current}
        className={classes.zIndex}
        role={undefined}
        transition
        disablePortal
        popperOptions={{
          modifiers: [{ name: 'offset', options: { offset: [0, 14] } }],
        }}
      >
        {({ TransitionProps }) => (
          <Transitions in={open} {...TransitionProps}>
            <Paper>
              <ClickAwayListener onClickAway={handleClose}>
                <MainCard
                  border={false}
                  elevation={16}
                  content={false}
                  boxShadow
                  shadow={theme.shadows[16]}
                >
                  <List>
                    <ListItem className={classes.profileCardfirstTile}>
                      <ListItemAvatar>
                        <img
                          src={
                            user?.profilePhoto
                              ? user?.profilePhoto
                              : defaultProfilePicture
                          }
                          className={classes.profileIcon}
                          alt="userAvatar"
                        />
                      </ListItemAvatar>
                      <ListItemText
                        primary={user.name}
                        secondary={user.email}
                      />
                    </ListItem>
                    <Divider component="li" className={classes.dividerDiv} />
                    {menuItems.map((item, index) => renderProfile(item, index))}
                  </List>
                </MainCard>
              </ClickAwayListener>
            </Paper>
          </Transitions>
        )}
      </Popper>
      {/* {showPopup && <ThankYou setShowPopup={setShowPopup} />} */}
      {/* {showTransactionHistoryPopup && (
        <TransactionHistoryPopup
          handleTransactionHistoryPopupClose={
            handleTransactionHistoryPopupClose
          }
        />
      )} */}
    </>
  );
};

export default ProfileSection;
