import React, { useCallback, useEffect, useState } from "react";
import {
  ActiveUserInfo,
  ActiveUserName,
  ActiveUserTopStrip,
  BackOptionMobile,
  ChatWindowTxt,
  RenameEditGroup,
  TopStripeInner,
  TopStripeLeft,
  TopStripeRight,
  UserTypingStatus,
} from "../../style";
import { Box, Divider, Input, useMediaQuery } from "@mui/material";
import { useTheme } from "@mui/material/styles";
import { useDispatch, useSelector } from "react-redux";
import {
  getPrivateChannel,
  getUserIdLocalStorage,
} from "@/components/common/common";
import { BASE_URL_CHAT } from "@/utils/staticValues";
import Auth from "@/auth/Auth";
import CloseOutlinedIcon from "@mui/icons-material/CloseOutlined";
import CheckOutlinedIcon from "@mui/icons-material/CheckOutlined";
import { LightTooltip } from "@/components/common/Tooltip/tooltip";
import {
  setActiveUser,
  setShowGroupInformationSection,
  setUsersList,
} from "@/hooks/ChatReducer";
import KeyboardArrowLeftRoundedIcon from "@mui/icons-material/KeyboardArrowLeftRounded";
import UserBadge from "../../common/components/user-badge";
import { showAlert } from "@/components/common/sweetAlert";
/**
 *
 * @param {boolean} param0 status of typing
 * @param param1 LogedIn User's ID
 * @param param2 TYping User ID
 * @returns {JSX.Element} Active User top profile section.
 */
function ProfileSection(props) {
  const [isGroupNameEdit, setIsGroupNameEdit] = useState(false);
  const [updatedGroupName, setUpdatedGroupName] = useState("");
  const [showScreen, setShowScreen] = useState(true);
  const { handleDraw, isAdmin = false, handleMobileToggleSection } = props;
  const [isTypingIndicator, setIsTyping] = useState(false);
  const [typingUser, setTypingUser] = useState<any>(null);

  const dispatch = useDispatch();
  const {
    detail: {
      data: { seller_name = "" },
    },
  } = useSelector((state: any) => state.productDetail);
  const { typing, activeUser, chats, usersList, showGroupInformation } =
    useSelector((state: any) => state.chatData);
  const { isTyping, userId: typingUserId } = typing;
  const {
    id,
    name,
    companyName,
    room_id,
    is_group,
    display_name = "",
    group_id,
    is_transfer,
    group_users,
  } = activeUser;

  useEffect(() => {
    let profileName;
    if (is_group == 1 && is_transfer !== 1) {
      profileName = display_name;
    } else {
      profileName = name ? name : seller_name;
    }
    setUpdatedGroupName(profileName);
  }, [display_name, name, seller_name, is_group]);

  let typingTimeoutId = null;

  useEffect(() => {
    let echoInstance;
    if (activeUser?.room_id) {
      echoInstance = getPrivateChannel(activeUser?.room_id);
      echoInstance.listenForWhisper("typing", (e) => {
        const { userID, roomId, userName = "" } = e;
        if (+activeUser?.is_blocked === 1) {
          return;
        }
        const typingTimeout = 2000;

        if (typingTimeoutId) {
          clearTimeout(typingTimeoutId);
        }

        if (+roomId === +activeUser?.room_id) {
          setIsTyping(true);
          setTypingUser({ id: userID, name: userName });
        }

        typingTimeoutId = setTimeout(() => {
          setIsTyping(false);
          setTypingUser(null);
          typingTimeoutId = null;
        }, typingTimeout);
      });
    }

    // Cleanup function to remove the listener
    return () => {
      if (echoInstance) {
        echoInstance.stopListeningForWhisper("typing");
      }
    };
  }, [activeUser?.is_blocked, activeUser?.room_id]);
  const currentLoggedUserId = getUserIdLocalStorage();

  useEffect(() => {
    dispatch(setShowGroupInformationSection(true));
  }, []);

  const updateGroupName = async () => {
    const response = await fetch(`${BASE_URL_CHAT}update-group-name-or-user`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${Auth?.token()}`,
      },
      body: JSON.stringify({ name: updatedGroupName, room_id: room_id }),
    });

    const updatedUserList = usersList.map((user) => {
      if (user?.group_id === group_id) {
        return {
          ...user,
          display_name: updatedGroupName,
        };
      }
      return user;
    });
    const updatedActiveUser = { ...activeUser, display_name: updatedGroupName };

    dispatch(setUsersList(updatedUserList));
    dispatch(setActiveUser(updatedActiveUser));
    setIsGroupNameEdit(false);
  };

  const handleGroupName = (event) => {
    const { value } = event?.target;
    setUpdatedGroupName(value);
  };

  const handleCancelNameChange = () => {
    setIsGroupNameEdit(false);
    // setUpdatedGroupName(name ? name : seller_name);
  };

  const handleShowGroupInfo = () => {
    dispatch(setShowGroupInformationSection(!showGroupInformation));
  };

  const theme = useTheme();
  const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm"));

  const handleBackClick = useCallback(() => {
    setShowScreen(false);
    setTimeout(() => {
      handleMobileToggleSection();
    });
  }, []);

  const handleCallClick = useCallback((type = "") => {
    const alertType = type === "call" ? "Voice Call" : "Video Call";
    const titleContent = "Coming Soon";
    const textContent = `${alertType} feature will be available soon.`;
    showAlert({ textContent, titleContent });
  }, []);

  const isGroupOrNotTransferredChat =
    is_group === 1 && is_transfer !== 1 && group_users?.length > 2;

  return (
    <div>
      <ActiveUserTopStrip>
        <TopStripeInner>
          <TopStripeLeft>
            {isSmallScreen && (
              <BackOptionMobile onClick={handleBackClick}>
                <KeyboardArrowLeftRoundedIcon />
              </BackOptionMobile>
            )}
            <Box>
              {id || (chats && chats?.length !== 0) ? (
                <ActiveUserInfo alignItems={"center"}>
                  {/* //change here please check ma'am  alignItems={'center'}*/}

                  {isGroupOrNotTransferredChat ? (
                    <Box
                      style={{
                        height: "34px",
                        width: "34px",
                        borderRadius: "50%",
                        boxShadow: " 0px 4px 4px 0px #00000040 inset",
                        gap: "10px",
                        backgroundColor: "#EDEDED",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                      }}
                    >
                      <img
                        alt={name}
                        src="/assets/chat/groupicon.svg"
                        style={{ height: "25px" }}
                        loading="lazy"
                      />
                    </Box>
                  ) : (
                    <UserBadge user={activeUser} status={activeUser?.online} />
                  )}
                  <Box sx={{}}>
                    {!isGroupNameEdit ? (
                      <ActiveUserName>
                        {updatedGroupName}

                        {is_group === 1 && is_transfer !== 1 && (
                          <RenameEditGroup>
                            <LightTooltip
                              arrow
                              disableInteractive
                              title="Rename Group Name"
                            >
                              <img
                                src="/assets/chat/edit.svg"
                                style={{ width: "12px" }}
                                onClick={() => {
                                  setIsGroupNameEdit(!isGroupNameEdit);
                                }}
                              />
                            </LightTooltip>

                            <Divider
                              orientation="vertical"
                              variant="middle"
                              flexItem
                              sx={{ margin: "3px 0", borderColor: "#dcb8b8" }}
                            />
                            <LightTooltip
                              arrow
                              disableInteractive
                              title="Group Information"
                            >
                              <img
                                src="/assets/chat/add.png"
                                style={{ width: "16px" }}
                                onClick={
                                  isAdmin ? handleDraw : handleShowGroupInfo
                                }
                              />
                            </LightTooltip>
                          </RenameEditGroup>
                        )}
                      </ActiveUserName>
                    ) : (
                      <>
                        {/* <input
                        type="text"
                        value={updatedGroupName}
                        onChange={handleGroupName}
                      /> */}
                        <Box
                          sx={{
                            display: "flex",
                            alignItems: "center",
                            "& svg": {
                              fontSize: "16px",
                            },
                          }}
                        >
                          <Input
                            placeholder="Placeholder"
                            value={updatedGroupName}
                            onChange={handleGroupName}
                            sx={{
                              color: "#fff",
                              border: "#fff",
                              fontSize: "14px",
                              "&.MuiInputBase-root::after": {
                                borderBottom: "none",
                              },
                              "&.MuiInput-root::after": {
                                borderBottom: "none",
                              },
                              "&.MuiInputBase-root::before": {
                                borderBottom: "1px solid #fff",
                              },
                              "&:hover:not(.Mui-disabled, .Mui-error)::before":
                                {
                                  borderBottom: "1px solid #fff",
                                },
                            }}
                          />
                          <LightTooltip arrow disableInteractive title="Cancel">
                            <CloseOutlinedIcon
                              sx={{ color: "#d7282f", cursor: "pointer" }}
                              onClick={handleCancelNameChange}
                            ></CloseOutlinedIcon>
                          </LightTooltip>
                          <Box
                            sx={{
                              height: "15px",
                              backgroundColor: "#fff",
                              width: "1px",
                              margin: "0px 4px",
                            }}
                          ></Box>
                          <LightTooltip arrow disableInteractive title="Save">
                            <CheckOutlinedIcon
                              sx={{ color: "#0ABB75", cursor: "pointer" }}
                              onClick={updateGroupName}
                            >
                              save
                            </CheckOutlinedIcon>
                          </LightTooltip>
                        </Box>
                      </>
                    )}
                    <UserTypingStatus>
                      {isTypingIndicator
                        ? "Typing..."
                        : is_group !== 1
                        ? companyName
                        : ""}
                    </UserTypingStatus>
                  </Box>
                </ActiveUserInfo>
              ) : (
                <ChatWindowTxt>Chat Windows</ChatWindowTxt>
              )}
            </Box>
          </TopStripeLeft>
          {chats.length !== 0 && (
            <TopStripeRight>
              <i
                className="icon-chat-call"
                onClick={() => handleCallClick("call")}
              ></i>
              <i
                className="icon-chat-video"
                onClick={() => handleCallClick()}
              ></i>
              {isAdmin ? (
                <img src={"assets/chat/person-icon.svg"} onClick={handleDraw} />
              ) : null}
            </TopStripeRight>
          )}
        </TopStripeInner>
      </ActiveUserTopStrip>
    </div>
  );
}

export default ProfileSection;
