import React, { useEffect, useState } from "react";
import {
  ChatUserMessage,
  ChatUserName,
  ImgBox,
  MessageBoxWuithIcon,
  MessageContent,
  MessageNumber,
  OutlinedButton,
  SelectFormButton,
  TextSeven,
} from "./style";
import { Avatar, Box, List, ListItem, ListItemAvatar, ListItemText, Skeleton, styled } from "@mui/material";
import Badge from "@mui/material/Badge";
import { fetchMoreUserList, filterUnreadMessages } from "../common";
import { BASE_URL_CHAT } from "@/utils/staticValues";
import Auth from "@/auth/Auth";
import { chatWindowPopup } from "@/hooks/ChatReducer";
import { useDispatch } from "react-redux";
import dynamic from "next/dynamic";
import useInitiateChatAndOpenWindow from "@/components/Chat/common/customHooks/useInitiateChat";
import { useRouter } from "next/router";
const EmptyChatUserLists = dynamic(
  () =>
    import(
      "@/components/Chat/common/components/empty-chat-userlist/EmptyChatUserLists"
    ),
  {
    ssr: false,
  }
);
const StyledBadge = styled(Badge)(({ theme }) => ({
  "& .MuiBadge-badge": {
    backgroundColor: "#44b700",
    color: "#44b700",
    boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
    padding: 0,
    width: "6px !important",
    height: "6px !important",
    minWidth: "auto",
  },
}));

function MessagesPopupData(props) {
  const { setAnchorMenuMessage, currentLoggedUserId } = props;
  const [chatList, setChatList] = useState([]);
  const [skeleton, setSkeleton] = useState(false);
  const router = useRouter();
  const dispatch = useDispatch();
  const initiateChat = useInitiateChatAndOpenWindow();

  useEffect(() => {
    const fetchUseList = async () => {
      setSkeleton(true);
      try {
        const response = await fetch(`${BASE_URL_CHAT}user-list`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${Auth.token()}`,
          },
        });
        const { data: { data = [] } = {} } = await response.json();
        const unreadUsersList = filterUnreadMessages(data);
        setChatList(unreadUsersList);
      } catch (err) {
        console.log("Error while fetching the user list", err);
      }
      setSkeleton(false);
    };
    fetchUseList();
  }, []);

  return (
    <div
      onMouseLeave={() => {
        setAnchorMenuMessage(null);
      }}
    >
      {skeleton ? (
        <>
          <List>
            {[...Array(4)].map((_, index) => (
              <ListItem key={index} alignItems="flex-start" sx={{ padding: 0 }}>
                <ListItemAvatar sx={{ minWidth: '45px' }}>
                  <Skeleton variant="circular" width={32} height={32} />
                </ListItemAvatar>
                <ListItemText
                  primary={
                    <Skeleton variant="text" width="50%" />
                  }
                  secondary={
                    <Skeleton variant="text" width="80%" />
                  }
                />
              </ListItem>
            ))}
          </List>
        </>
      ) : chatList?.length > 0 ? (
        <>
          {chatList?.slice(0, 4).map((chat) => (
            <>
              <MessageContent>
                <ImgBox>
                  <StyledBadge
                    overlap="circular"
                    anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
                    variant="dot"
                  >
                    <Avatar alt="" src={chat?.avatar_original} />
                  </StyledBadge>
                </ImgBox>
                <MessageBoxWuithIcon
                  onClick={() => initiateChat(chat?.id, currentLoggedUserId)}
                >
                  <ChatUserName>
                    {chat?.name}
                    <ChatUserMessage>
                      {chat?.message ?? "Chat not initiated"}
                    </ChatUserMessage>
                  </ChatUserName>
                  {chat?.unread_count > 0 && (
                    <MessageNumber>
                      <TextSeven>{chat?.unread_count}</TextSeven>
                    </MessageNumber>
                  )}
                </MessageBoxWuithIcon>
              </MessageContent>
            </>
          ))}
          <OutlinedButton
            fullWidth
            variant="contained"
            disabled={chatList?.length < 1}
            onClick={() => router.push("/chat")}
          >
            View Details
          </OutlinedButton>
        </>
      ) : (
        <Box>
        <EmptyChatUserLists title="No New Messages" imageURL ="/assets/images/header/No-message-header.svg" imageWidth="100px"/>
        </Box>
      )}
    </div>
  );
}

export default MessagesPopupData;
