import Auth from "@/auth/Auth";
import {
  Admin,
  BorderBox,
  Box1,
  ButtonBox,
  ChatBox,
  Circul,
  GroupChat,
  GroupChatID,
  GroupChatName,
  GroupMember,
  GroupMember1,
  ImgIcon,
  LeaveButton,
  Member,
  MutBox,
  MutText,
  NameBox,
  NameandImage,
  NotificationTxtBox,
  NotificationsBox,
  PinBox,
  ProductChat,
} from "@/components/ChatModule/style";
import {
  getUserIdLocalStorage,
  handlePinUnpinUserToTop,
} from "@/components/common/common";
import { showAlert } from "@/components/common/sweetAlert";
import { Android12Switch } from "@/components/pricingSettings/style";
import {
  replaceChat,
  setActiveUser,
  setShowGroupInformationSection,
  setUsersList,
} from "@/hooks/ChatReducer";
import { BASE_URL_CHAT } from "@/utils/staticValues";
import {
  Box,
  FormControlLabel,
  FormGroup,
  Grid,
  Typography,
  styled,
  Switch,
} from "@mui/material";
import React, { useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";

const AntSwitch = styled(Switch)(({ theme }) => ({
  width: 28,
  height: 16,
  padding: 0,
  display: "flex",
  "&:active": {
    "& .MuiSwitch-thumb": {
      width: 15,
    },
    "& .MuiSwitch-switchBase.Mui-checked": {
      transform: "translateX(9px)",
    },
  },
  "& .MuiSwitch-switchBase": {
    padding: 2,
    "&.Mui-checked": {
      transform: "translateX(12px)",
      color: "#fff",
      "& + .MuiSwitch-track": {
        opacity: 1,
        backgroundColor: theme.palette.mode === "dark" ? "#177ddc" : "#d7282f",
      },
    },
  },
  "& .MuiSwitch-thumb": {
    boxShadow: "0 2px 4px 0 rgb(0 35 11 / 20%)",
    width: 12,
    height: 12,
    borderRadius: 6,
    background: "#fff",
    transition: theme.transitions.create(["width"], {
      duration: 200,
    }),
  },
  "& .MuiSwitch-track": {
    borderRadius: 16 / 2,
    opacity: 1,
    backgroundColor:
      theme.palette.mode === "dark"
        ? "rgba(255,255,255,.35)"
        : "rgba(0,0,0,.25)",
    boxSizing: "border-box",
  },
}));
export default function GroupInfoSection(props) {
  const { isAdminPage = false } = props;
  const gridItemSize = isAdminPage ? 3 : 4;
  const { activeUser, usersList } = useSelector((state: any) => state.chatData);
  const {
    display_name = "",
    group_id,
    group_users,
    id,
    is_pinned,
    room_id,
  } = activeUser;
  const dispatch = useDispatch();

  const currentLoggedUserId = getUserIdLocalStorage();

  const handleChangePinStatus = async (e) => {
    const updatedUserLists = await handlePinUnpinUserToTop({
      usersList,
      user: activeUser,
    });
    const activeUsersData = {
      ...activeUser,
      is_pinned: is_pinned == 0 ? 1 : 0,
    };

    dispatch(setActiveUser(activeUsersData));
    dispatch(setUsersList(updatedUserLists));
  };

  const handleLeaveGroupChat = async () => {
    try {
      const formDatas = new FormData();
      formDatas.append("room_id", activeUser?.room_id);
      formDatas.append("user_id", currentLoggedUserId);
      const response = await fetch(`${BASE_URL_CHAT}selfExitGroup`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${Auth.token()}`,
        },
        body: formDatas,
      });
      if (response?.ok) {
        const updateduserList = usersList?.filter(
          (user) => user?.room_id !== activeUser?.room_id
        );
        const isActiveUserInRoom = ({ activeUser }: any) => {
          return (
            activeUser &&
            typeof activeUser === "object" &&
            Object.keys(activeUser).length > 0 &&
            activeUser?.room_id
          );
        };
        if (isActiveUserInRoom({ activeUser })) {
          dispatch(setActiveUser({}));
          dispatch(replaceChat([]));
        }
        dispatch(setUsersList(updateduserList));
        dispatch(setShowGroupInformationSection(true));
      }

      // if (response?.ok) {
      //   console.log(response, "left");
      //   const updatedUsersList = usersList.filter(
      //     (user, index) => user?.room_id !== activeUser?.room_id
      //   );
      //   dispatch(setUsersList(updatedUsersList));
      // }
    } catch (error) {
      console.error("Error while Leave Group Chat", error);
    }
  };

  const filterAdminUserToTop = useMemo(() => {
    return [...(group_users ?? [])]?.sort((a, b) => b.is_owner - a.is_owner);
  }, [group_users]);

  return (
    <Box>
      <ChatBox>
        {/* <ChatInFo sx={{ margin: `${!isAdminPage ? "12px 0 4px 0" : ""}` }}>
          Chat Info
        </ChatInFo> */}
        <BorderBox></BorderBox>
        <ProductChat>
          <Circul>
            <ImgIcon>
              <img src="/assets/chat/groupicon.svg" alt="" />
            </ImgIcon>
          </Circul>
          <GroupChat>
            <GroupChatName>{display_name}</GroupChatName>
            <GroupChatID>Group ID: {group_id} </GroupChatID>
          </GroupChat>
        </ProductChat>
        <BorderBox></BorderBox>
        <GroupMember>
          <Member>
            <GroupMember1>
              Group Member ({filterAdminUserToTop?.length})
            </GroupMember1>
          </Member>
          <Box sx={{ margin: "10px 0" }}>
            <Grid container spacing={1}>
              {filterAdminUserToTop?.map((user, index) => (
                <Grid item xs={gridItemSize} key={index}>
                  <NameandImage>
                    <Box1>
                      <img src="/assets/chat/groupicon.svg" alt="" />
                    </Box1>
                    <NameBox>{user?.name}</NameBox>
                    <Admin sx={{}}>
                      <Typography sx={{}}>
                        {user?.is_owner === 1 && "Admin"}
                      </Typography>
                    </Admin>
                  </NameandImage>
                </Grid>
              ))}
            </Grid>
          </Box>
        </GroupMember>
        <NotificationsBox>
          <MutBox>
            <NotificationTxtBox>
              <MutText sx={{ fontSize: `${!isAdminPage ? "12px" : "14px"}` }}>
                Mute Notifications
              </MutText>
            </NotificationTxtBox>
            <Box sx={{ margin: "6px 0 0 0" }}>
              <FormGroup>
                <FormControlLabel
                  control={
                    <Android12Switch
                      // defaultChecked={is_pinned == 0 ? false : true}
                      // disabled={true}
                      // value={is_pinned == 0}
                      onChange={(e) => {
                        const titleContent = "Coming Soon";
                        const textContent = `Mute notification feature will be available soon.`;
                        showAlert({ textContent, titleContent });
                      }}
                    />
                  }
                  label=" "
                />
              </FormGroup>
            </Box>
          </MutBox>
          <PinBox>
            <NotificationTxtBox>
              <MutText sx={{ fontSize: `${!isAdminPage ? "12px" : "14px"}` }}>
                Pin to Top
              </MutText>
            </NotificationTxtBox>
            <Box sx={{ margin: "6px 0 0 0" }}>
              <FormGroup>
                <FormControlLabel
                  control={
                    <Android12Switch
                      defaultChecked={is_pinned == 0 ? false : true}
                      value={is_pinned == 0}
                      onChange={(e) => handleChangePinStatus(e)}
                    />
                  }
                  label=" "
                />
              </FormGroup>
            </Box>
          </PinBox>
        </NotificationsBox>
        <ButtonBox>
          <LeaveButton
            sx={{ fontSize: `${!isAdminPage ? "12px" : "14px"}` }}
            onClick={handleLeaveGroupChat}
          >
            Leave Group Chat
          </LeaveButton>
          <LeaveButton sx={{ fontSize: `${!isAdminPage ? "12px" : "14px"}` }}>
            Leave and End The Chat
          </LeaveButton>
        </ButtonBox>
      </ChatBox>
    </Box>
  );
}
