import React, { useEffect, useState } from "react";
import {
  Avatar,
  Badge,
  Box,
  Button,
  IconButton,
  Menu,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../components/grid/Grid";
import {
  ROUTE_GENERAL_MESSAGES,
  ROUTE_GENERAL_SUPPORT,
  ROUTE_GENERAL_TICKET_LIST,
  ROUTE_GENERAL_TRAINING,
  ROUTE_GENERAL_USER_PROFILE,
} from "../../routes/routes";
import PermPhoneMsgIcon from "@mui/icons-material/PermPhoneMsg";
import EmailIcon from "@mui/icons-material/Email";
import { useNavigate } from "react-router-dom";
import AccountCircleRoundedIcon from "@mui/icons-material/AccountCircleRounded";
import ExitToAppIcon from "@mui/icons-material/ExitToApp";
import {
  BACKDROP_HIDE,
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../lib/redux/slices/appSlice";
import {
  LOG_OUT,
  SET_ADMIN_TOKEN,
  SET_SELECTED_ROLE,
  SET_SELECTED_SUB_USER,
} from "../../lib/redux/slices/userSlice";
import PlayCircleIcon from "@mui/icons-material/PlayCircle";
import KeyboardReturnIcon from "@mui/icons-material/KeyboardReturn";
import DraftsIcon from "@mui/icons-material/Drafts";
import { motion } from "framer-motion";
import { getUnseenMessages } from "../../features/authentication/services/getUnseenMessage";
import { ChevronLeft } from "@mui/icons-material";

export const HeaderOperations = () => {
  const [anchorEl, setAnchorEl] = useState(null);
  const open = Boolean(anchorEl);
  const dispatch = useDispatch();
  const userProfile = useSelector((state) => state.userSlice.loginUserProfile);
  const navigate = useNavigate();

  const handleMenuToggle = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const [unseenMessages, setUnseenMessages] = useState({
    state: false,
    num: 0,
  });
  const role = useSelector((state) => state.userSlice.role);

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  useEffect(() => {
    dispatch(getUnseenMessages())
      .then((r) => {
        if (r?.payload?.data) {
          setUnseenMessages(r.payload.data);
        }
      })
      .catch((error) => {
        console.error("Error fetching unseen messages:", error);
        setUnseenMessages({
          state: false,
          num: 0,
        });
      });
  }, [dispatch]);

  function stringAvatar(name) {
    if (name) {
      const nameArr = name
        ?.split(" ")
        ?.filter((item) => item)
        ?.map((item) => item[0]);
      return {
        sx: {
          bgcolor: "#353b48",
        },
        children: nameArr[0],
      };
    }
    return {};
  }

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: { xs: "flex-start", sm: "center" },
        padding: { xs: "0 16px", sm: "0" },
        minWidth: "fit-content",
      }}
    >
      <Tooltip placement="bottom" title="مدیریت تیکت">
        <IconButton
          sx={{ color: "white" }}
          onClick={() => {
            navigate(ROUTE_GENERAL_TICKET_LIST);
          }}
        >
          {unseenMessages?.state ? (
            <motion.div
              initial={{ y: 0 }}
              animate={{ y: [0, -2, 0] }}
              transition={{
                duration: 0.5,
                repeat: Infinity,
                repeatType: "loop",
              }}
            >
              <Badge
                badgeContent={unseenMessages?.num}
                color="error"
                anchorOrigin={{
                  vertical: "top",
                  horizontal: "left",
                }}
              >
                <DraftsIcon sx={{ fontSize: 26 }} />
              </Badge>
            </motion.div>
          ) : (
            <DraftsIcon sx={{ fontSize: 26 }} />
          )}
        </IconButton>
      </Tooltip>

      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 0.5,
          cursor: "pointer",
        }}
        aria-controls={open ? "app-menu" : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleMenuToggle}
      >
        <IconButton
          sx={{
            color: "white",
          }}
        >
          <AccountCircleRoundedIcon sx={{ fontSize: 26 }} />
        </IconButton>
        <Box
          sx={{
            display: { xs: "none", sm: "flex" },
            flexDirection: "column",
            alignItems: "flex-start",
            color: "white",
            minWidth: "fit-content",
          }}
        >
          <Typography
            variant="body2"
            sx={{ fontWeight: "bold", fontSize: 11.5, minWidth: "fit-content" }}
          >
            {userProfile?.fullname || "-"}
          </Typography>
          <Typography variant="caption" sx={{ fontSize: 11, mt: -0.5 }}>
            {userProfile?.mobile || "-"}
          </Typography>
        </Box>
      </Box>

      <Menu
        disableScrollLock={true}
        id="app-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleMenuClose}
        PaperProps={{
          sx: {
            width: { xs: "90%", sm: "auto" },
            height: { xs: "50vh", sm: "auto" },
            borderRadius: 2,
            boxShadow: 3,
            overflowY: "auto",
          },
        }}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "center",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "center",
        }}
      >
        <Box
          display={"flex"}
          justifyContent="space-between"
          alignItems="center"
          px={1.4}
          pb={1.4}
          gap={4}
          onClick={() => {
            navigate(ROUTE_GENERAL_USER_PROFILE);
            handleMenuClose();
          }}
          sx={{
            cursor: "pointer",
          }}
        >
          <Grid container gap={1} alignItems="center">
            {userProfile?.image &&
            userProfile?.image !== "empty" &&
            userProfile?.fullname ? (
              <Avatar
                alt="User Profile"
                src={userProfile?.image}
                color="secondary"
                sx={{ width: 32, height: 32 }}
              />
            ) : (
              <Avatar
                {...stringAvatar(userProfile?.fullname)}
                sx={{ width: 32, height: 32 }}
              />
            )}
            <Grid direction="column">
              <Typography
                variant="body1"
                style={{
                  fontSize: 13,
                  lineHeight: 0.7,
                }}
                mt={0.5}
              >
                {userProfile?.fullname}
              </Typography>
              <Typography
                variant="caption"
                color={"#666"}
                style={{
                  fontSize: 11,
                }}
              >
                موبایل: {userProfile?.mobile}
              </Typography>
            </Grid>
          </Grid>
          <ChevronLeft sx={{ fontSize: 20, mr: -1 }} />
        </Box>

        <Grid
          direction="column"
          gap={1}
          px={1}
          py={0.5}
          sx={{
            borderTop: "1px solid #f0f0f0",
            borderBottom: "1px solid #f0f0f0",
          }}
        >
          {/* <Button
            startIcon={<AccountBoxIcon sx={{ fontSize: 34 }} />}
            color="primary"
            fullWidth
            onClick={() => {
              navigate(ROUTE_GENERAL_USER_PROFILE);
              handleMenuClose();
            }}
            variant="text"
            sx={{
              justifyContent: "flex-start",
              fontSize: 14,
            }}
          >
            پروفایل
          </Button> */}
          <Grid container justifyContent="center">
            <Button
              startIcon={<EmailIcon />}
              color="primary"
              fullWidth
              onClick={() => {
                navigate(ROUTE_GENERAL_MESSAGES);
                handleMenuClose();
              }}
              variant="text"
              sx={{
                justifyContent: "flex-start",
                fontSize: 12,
              }}
            >
              پیام های شما
            </Button>
          </Grid>
          {role?.includes("KillHouse") && (
            <Grid container justifyContent="center">
              <Button
                startIcon={<PlayCircleIcon />}
                color="primary"
                fullWidth
                onClick={() => {
                  navigate(ROUTE_GENERAL_TRAINING);
                  handleMenuClose();
                }}
                variant="text"
                sx={{
                  justifyContent: "flex-start",
                  fontSize: 12,
                }}
              >
                آموزش
              </Button>
            </Grid>
          )}

          <Grid container justifyContent="center">
            <Button
              startIcon={<PermPhoneMsgIcon />}
              color="primary"
              fullWidth
              onClick={() => {
                navigate(ROUTE_GENERAL_SUPPORT);
                handleMenuClose();
              }}
              variant="text"
              sx={{
                justifyContent: "flex-start",
                fontSize: 12,
              }}
            >
              پشتیبانی
            </Button>
          </Grid>
        </Grid>
        <Grid
          container
          justifyContent="center"
          alignItems="center"
          px={1.4}
          py={1}
        >
          <Button
            startIcon={<ExitToAppIcon sx={{ fontSize: 16 }} />}
            variant="outlined"
            fullWidth
            sx={{
              fontSize: 12,
              padding: "3px 0px",
            }}
            color="error"
            onClick={() => {
              dispatch(DRAWER({ right: false, bottom: false, content: null }));
              handleMenuClose();
              dispatch(
                OPEN_MODAL({
                  title: "مایل به خروج از سامانه هستید؟",
                  size: "320px",
                  content: (
                    <Grid
                      container
                      xs={12}
                      justifyContent="space-around"
                      sx={{ maxWidth: "320px" }}
                    >
                      <Grid item container xs={4}>
                        <Button
                          fullWidth
                          color="error"
                          variant="contained"
                          startIcon={<ExitToAppIcon />}
                          onClick={() => {
                            handleMenuClose();
                            dispatch(BACKDROP_HIDE());
                            dispatch(CLOSE_MODAL());
                            dispatch(SET_ADMIN_TOKEN(null));
                            dispatch(LOG_OUT());
                            dispatch(SET_SELECTED_SUB_USER(null));
                            dispatch(SET_SELECTED_ROLE(null));
                            // window.location = "https://rasadyaar.ir/?exit=1";
                          }}
                        >
                          بله
                        </Button>
                      </Grid>
                      <Grid item container xs={4}>
                        <Button
                          fullWidth
                          startIcon={<KeyboardReturnIcon />}
                          variant="outlined"
                          onClick={() => {
                            dispatch(CLOSE_MODAL());
                          }}
                        >
                          لغو
                        </Button>
                      </Grid>
                    </Grid>
                  ),
                })
              );
            }}
          >
            خروج
          </Button>
        </Grid>
      </Menu>
    </Box>
  );
};
