import { Box, Grid, Link, Tab, Typography } from "@mui/material";
import React, { useCallback, useEffect, useState } from "react";
import { ProfileHeader } from "@/components/common/profileheader";
import Head from "next/head";
import UserList from "../Chat/userList/index";
import ChatRoom from "../Chat/chatRoom";
import "../../components/ProductDetail/ProductComponents/Style";
import "../../components/ProductDetail/style";
import {
  AllInformationSection,
  AvtartDetail,
  BasicInfoDetail,
  BasicInfoDetailInner,
  BoldHeadings,
  BusinessTypeDetail,
  ChatDrawerStyle,
  ChatTabText,
  ChatTabs,
  CommonHeading,
  DetailHeading,
  DetailValue,
  EmptyBigChatRoomLeft,
  EmptyBigChatRoomRight,
  EmptySellerIcon,
  EmptySellerImage,
  EmptyUserList,
  FullWebChatOuter,
  InfoRowItem,
  OuterBoxTab,
  OuterChatContainer,
  RightSideChatSection,
  SCompanyDetail,
  ScrollDiv,
  SellerDetailOuter,
  SellerName,
  SellerNameDetail,
  SelletHeaderInfo,
  SubText,
} from "./style";
import { styled, useTheme } from "@mui/material/styles";
import Drawer from "@mui/material/Drawer";
import MuiAppBar, { AppBarProps as MuiAppBarProps } from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import CssBaseline from "@mui/material/CssBaseline";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import Badge from "@mui/material/Badge";
import Avatar from "@mui/material/Avatar";
import PersonAddIcon from "@mui/icons-material/PersonAdd";
import MediaTab from "./MediaTab";
import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import {
  InnColumn,
  ManufacturerYearBox,
} from "../ProductDetail/ProductComponents/Style";
import { LightTooltip } from "../common/Tooltip/tooltip";
import { countryDetail, createPrivateChannel } from "../common/common";
import GroupInformationSection from "../Chat/userList/group-chat/groupInformations";
import { updateUserListWithMessage } from "../Chat/common/commonFunctions";
import { setUsersList } from "@/hooks/ChatReducer";
import { BROWSER_TAB } from "@/utils/staticValues";
interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}
function CustomTabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ padding: "12px" }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}
function a11yProps(index: number) {
  return {
    id: `simple-tab-${index}`,
    "aria-controls": `simple-tabpanel-${index}`,
  };
}

const SmallAvatar = styled(Avatar)(({ theme }) => ({
  width: 22,
  height: 22,
  border: `2px solid ${theme.palette.background.paper}`,
}));
const drawerWidth = 400;
const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })<{
  open?: boolean;
}>(({ theme, open }) => ({
  flexGrow: 1,
  // padding: theme.spacing(3),
  transition: theme.transitions.create("margin", {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  // marginRight: open ? drawerWidth : 0,
  // width: "100%",
  // width: `calc(100% - ${drawerWidth}px)`,

  ...(open && {
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
    marginRight: 0,
  }),
  position: "relative",
}));

interface AppBarProps extends MuiAppBarProps {
  open?: boolean;
}

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== "open",
})<AppBarProps>(({ theme, open }) => ({
  transition: theme.transitions.create(["margin", "width"], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  ...(open && {
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(["margin", "width"], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
    marginRight: drawerWidth,
  }),
}));

const DrawerHeader = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
  justifyContent: "flex-start",
  margin: "-15px 1px 0 -43px",
  position: "absolute",
  "& button": {
    background: "#fff !Important",
    borderRadius: "3px",
    // boxShadow: "rgba(0, 0, 0, 0.15) 1.95px 1.95px 0 1.95px",
    boxShadow: "19px 0 11px -23px rgba(0,0,0,0.27) inset",
    svg: {
      color: "#d7282f",
    },
  },
}));

const OnlineBadge = styled(Badge)(({ theme }) => ({
  "& .MuiBadge-badge": {
    backgroundColor: "#44b700",
    color: "#44b700",
    boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
    "&::after": {
      position: "absolute",
      top: 0,
      left: 0,
      // width: "100%",
      // height: "100%",
      width: "6px",
      height: "6px",
      borderRadius: "50%",
      animation: "ripple 1.2s infinite ease-in-out",
      border: "1px solid currentColor",
      content: '""',
    },
  },
  "@keyframes ripple": {
    "0%": {
      transform: "scale(.8)",
      opacity: 1,
    },
    "100%": {
      transform: "scale(2.4)",
      opacity: 0,
    },
  },
}));

const OfflineBadge = styled(Badge)(({ theme }) => ({
  "& .MuiBadge-badge": {
    backgroundColor: "#d7282f",
    color: "#44b700",
    boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
    "&::after": {
      position: "absolute",
      top: 0,
      left: 0,
      width: "100%",
      height: "100%",
      borderRadius: "50%",
      // animation: "ripple 1.2s infinite ease-in-out",
      // border: "1px solid currentColor",
      content: '""',
    },
  },
  "@keyframes ripple": {
    "0%": {
      transform: "scale(.8)",
      opacity: 1,
    },
    "100%": {
      transform: "scale(2.4)",
      opacity: 0,
    },
  },
}));

function ChatAdmin() {
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);
  const { userProfile, activeUser, usersList } = useSelector(
    (state: any) => state?.chatData
  );
  const { is_group } = activeUser || {};
  const { user_info } = useSelector((state: any) => state?.userData);
  const { id: uniqueId } = user_info;
  const dispatch = useDispatch();

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };
  const [value, setValue] = React.useState(0);

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  let manufacturer_image = "s-badge.png";
  let bussinessType;
  console.log(userProfile?.userInfo?.business_type, "");

  if (
    userProfile?.userInfo?.business_type &&
    userProfile?.userInfo?.business_type !== "N/A"
  ) {
    bussinessType = JSON.parse(userProfile?.userInfo?.business_type)?.map(
      (item) => item?.name
    )[0];
  }

  if (bussinessType == "Manufacturer") {
    manufacturer_image = "manufacturer.svg";
  } else if (bussinessType == "Agents and Representative") {
    manufacturer_image = "Agent.svg";
  } else if (bussinessType == "Reseller") {
    manufacturer_image = "Re-seller.svg";
  } else if (bussinessType == "Distributor") {
    manufacturer_image = "Distributor.svg";
  } else if (bussinessType == "Retailer") {
    manufacturer_image = "Retailer.svg";
  } else if (bussinessType == "Others") {
    manufacturer_image = "other.svg";
  } else {
    manufacturer_image = "Wholesaler.svg";
  }

  const establishedYear = moment(userProfile?.userInfo?.created_at);
  const yearsDifference = moment().diff(moment(establishedYear), "years");
  const newMessage =
    yearsDifference < 1
      ? "<1 Year"
      : moment(establishedYear).fromNow()?.replaceAll("ago", "");
  let country_detail;
  if (userProfile?.userInfo?.country) {
    country_detail = countryDetail({
      key: "name",
      country_code: userProfile?.userInfo?.country,
    });
  }

  const updateUserListCallback = useCallback((e) => {
    const {
      userList: { data = {} },
      messageData,
    } = e || {};
    const updatedUserslist = updateUserListWithMessage(
      usersList,
      messageData,
      uniqueId,
      activeUser
    );
    dispatch(setUsersList(updatedUserslist));
  }, []);

  useEffect(() => {
    const channelName = "notifications";
    const eventPrefix = "UserNotification";
    const notificationEvent = createPrivateChannel(
      uniqueId,
      channelName,
      eventPrefix
    );
    notificationEvent.listen(eventPrefix, updateUserListCallback);

    return () => {
      if (notificationEvent?.channel) {
        notificationEvent?.channel.stopListening(
          eventPrefix,
          updateUserListCallback
        );
      }
    };
  }, [uniqueId]);

  return (
    <>
      <Head>
        <title>Chat - {BROWSER_TAB}</title>
      </Head>
      <div className="full_page">
        <Toolbar>
          {/* <IconButton
            color="inherit"
            aria-label="open drawer"
            edge="end"
            onClick={handleDrawerOpen}
            sx={{ ...(open && { display: 'none' }) }}
          >
            <MenuIcon />
          </IconButton> */}
        </Toolbar>
        <Drawer
          style={{
            width: "drawerWidth",
            flexShrink: 0,
          }}
          sx={ChatDrawerStyle}
          variant="persistent"
          anchor="right"
          open={open}
        >
          <DrawerHeader>
            <IconButton onClick={handleDrawerClose}>
              {theme?.direction === "rtl" ? (
                <ChevronLeftIcon />
              ) : (
                <CloseRoundedIcon sx={{ color: "#000" }} />
              )}
            </IconButton>
          </DrawerHeader>
          {is_group !== 1 ? (
            <>
              <SellerDetailOuter>
                <SelletHeaderInfo>
                  <AvtartDetail>
                    {userProfile?.isOnline ? (
                      <OnlineBadge
                        overlap="circular"
                        anchorOrigin={{
                          vertical: "bottom",
                          horizontal: "right",
                        }}
                        variant="dot"
                      >
                        <Avatar
                          alt={
                            userProfile?.userInfo?.name
                              ? userProfile?.userInfo?.name
                              : "NA"
                          }
                          src={
                            userProfile?.userInfo?.avatar_original
                              ? userProfile?.userInfo?.avatar_original
                              : userProfile?.userInfo?.name.charAt(0)
                          }
                        />
                      </OnlineBadge>
                    ) : (
                      <OfflineBadge
                        overlap="circular"
                        anchorOrigin={{
                          vertical: "bottom",
                          horizontal: "right",
                        }}
                        variant="dot"
                      >
                        <Avatar
                          alt={
                            userProfile?.userInfo?.name
                              ? userProfile?.userInfo?.name
                              : "NA"
                          }
                          src={
                            userProfile?.userInfo?.avatar_original
                              ? userProfile?.userInfo?.avatar_original
                              : userProfile?.userInfo?.name.charAt(0)
                          }
                        />
                      </OfflineBadge>
                    )}
                    <SellerNameDetail>
                      <div>
                        <SellerName>
                          {userProfile?.userInfo?.name
                            ? userProfile?.userInfo?.name
                            : "NA"}
                        </SellerName>
                        <SCompanyDetail>
                          {userProfile?.basicInfo?.shop_name
                            ? userProfile?.basicInfo?.shop_name
                            : "NA"}
                        </SCompanyDetail>
                      </div>
                    </SellerNameDetail>
                  </AvtartDetail>
                  <PersonAddIcon className="personadd" />
                </SelletHeaderInfo>
                <BusinessTypeDetail>
                  {/* <img src="/assets/images/business-img.svg" /> */}

                  <ManufacturerYearBox>
                    {bussinessType && (
                      <InnColumn className="businessName">
                        <Box sx={{ display: "flex" }}>
                          <img
                            className="move-up"
                            src={`/assets/images/${manufacturer_image}`}
                            style={{
                              height: "16px",
                              margin: "-1px 3px 0px 1px",
                            }}
                          />

                          <LightTooltip
                            PopperProps={{ style: { zIndex: 10 } }}
                            disableInteractive
                            arrow
                            title=""
                            placement="top"
                          >
                            <Typography>{bussinessType}</Typography>
                          </LightTooltip>
                        </Box>
                      </InnColumn>
                    )}
                    <div className="yearbadge">
                      <InnColumn>
                        <LightTooltip
                          disableInteractive
                          arrow
                          title={`This supplier has a Power Cozmo Website account for ${newMessage == "<1 Year"
                            ? "less than year"
                            : newMessage
                            }.`}
                          placement="top"
                        >
                          <Typography
                            className={
                              bussinessType?.name == undefined ||
                                bussinessType?.name == ""
                                ? ""
                                : "dotBefore"
                            }
                          >
                            {newMessage}
                          </Typography>
                        </LightTooltip>
                      </InnColumn>
                      {userProfile?.userInfo?.plan_status?.display_name !=
                        "No Plan" && (
                          <InnColumn className="onlyimagecase">
                            <Typography
                              className="dotbeforeimg"
                            // className={plan_status_with_message?.display_name == 'Enterprise' ? 'dotbeforeimg enterdotbeforeimg' : 'dotbeforeimg'}
                            >
                              <img
                                src={userProfile?.userInfo?.plan_status?.icon}
                                alt={
                                  userProfile?.userInfo?.plan_status?.display_name
                                }
                                className={
                                  userProfile?.userInfo?.plan_status
                                    ?.display_name == "Enterprise"
                                    ? "typebusiness enterprisePlan"
                                    : "typebusiness"
                                }
                              />
                            </Typography>
                          </InnColumn>
                        )}
                    </div>
                  </ManufacturerYearBox>
                </BusinessTypeDetail>
              </SellerDetailOuter>
              <ScrollDiv>
                <AllInformationSection>
                  <BasicInfoDetail>
                    <CommonHeading>
                      <Typography variant="h2">Basic information</Typography>
                    </CommonHeading>
                    <BasicInfoDetailInner>
                      <Grid container spacing={1}>
                        <Grid item xs={12} sm={5} md={5}>
                          <InfoRowItem>
                            <DetailHeading>Country region</DetailHeading>
                            <DetailValue>
                              {userProfile?.userInfo?.country
                                ? country_detail
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={7} md={7}>
                          <InfoRowItem>
                            <DetailHeading>Business Type</DetailHeading>
                            <DetailValue>
                              {userProfile?.userInfo?.business_type &&
                                userProfile?.userInfo?.business_type !== "N/A"
                                ? JSON.parse(
                                  userProfile?.userInfo?.business_type
                                )?.map(
                                  (item, index, array) =>
                                    `${item?.name}${index === array?.length - 1 ? "" : ", "
                                    }`
                                )
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={5} md={5}>
                          <InfoRowItem>
                            <DetailHeading>Year Established</DetailHeading>
                            <DetailValue>
                              {userProfile?.basicInfo?.registration_year
                                ? userProfile?.basicInfo?.registration_year
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={7} md={7}>
                          <InfoRowItem>
                            <DetailHeading>Main Products</DetailHeading>
                            <DetailValue>
                              <Link>
                                {userProfile?.basicInfo?.company_products
                                  ? userProfile?.basicInfo?.company_products
                                  : "NA"}{" "}
                              </Link>
                              {/* <Link>
                            Diesel Pump
                          </Link> */}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={5} md={5}>
                          <InfoRowItem>
                            <DetailHeading>Location</DetailHeading>
                            <DetailValue>
                              {userProfile?.userInfo?.country
                                ? country_detail
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={7} md={7}>
                          <InfoRowItem>
                            <DetailHeading>Employee Count</DetailHeading>
                            <DetailValue>
                              {userProfile?.basicInfo?.no_of_employee
                                ? userProfile?.basicInfo?.no_of_employee
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={5} md={5}>
                          <InfoRowItem>
                            <DetailHeading>Annual Revenue</DetailHeading>
                            <DetailValue>
                              {userProfile?.basicInfo?.yearly_revenu
                                ? userProfile?.basicInfo?.yearly_revenu
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={7} md={7}>
                          <InfoRowItem>
                            <DetailHeading>Other Products</DetailHeading>
                            <DetailValue>
                              {userProfile?.basicInfo?.company_other_products
                                ? userProfile?.basicInfo?.company_other_products
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                      </Grid>
                    </BasicInfoDetailInner>
                  </BasicInfoDetail>
                  <BasicInfoDetail>
                    <CommonHeading>
                      <Typography variant="h2">Contact Information</Typography>
                    </CommonHeading>
                    <BasicInfoDetailInner>
                      <Grid container spacing={1}>
                        <Grid item xs={12} sm={5} md={5}>
                          <InfoRowItem>
                            <DetailHeading>Company No.</DetailHeading>
                            <DetailValue>
                              {userProfile?.contactInfo?.phone
                                ? `+${userProfile?.contactInfo?.mobile_code} - ${userProfile?.contactInfo?.phone}`
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={7} md={7}>
                          <InfoRowItem>
                            <DetailHeading>Email</DetailHeading>
                            <DetailValue>
                              {userProfile?.contactInfo?.shop_email
                                ? userProfile?.contactInfo?.shop_email
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={5} md={5}>
                          <InfoRowItem>
                            <DetailHeading>Mobile No.</DetailHeading>
                            <DetailValue>
                              {userProfile?.contactInfo?.phone
                                ? `+${userProfile?.contactInfo?.mobile_code} - ${userProfile?.contactInfo?.phone}`
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                        <Grid item xs={12} sm={7} md={7}>
                          <InfoRowItem>
                            <DetailHeading>Company Address</DetailHeading>
                            <DetailValue>
                              {userProfile?.contactInfo?.address &&
                                userProfile?.contactInfo?.city &&
                                userProfile?.contactInfo?.op_region_state_province
                                ? `${userProfile?.contactInfo?.address}, ${userProfile?.contactInfo?.city}, ${userProfile?.contactInfo?.op_region_state_province}`
                                : "NA"}
                            </DetailValue>
                          </InfoRowItem>
                        </Grid>
                      </Grid>
                    </BasicInfoDetailInner>
                  </BasicInfoDetail>
                </AllInformationSection>
                <OuterBoxTab>
                  <Box sx={{ width: "100%" }}>
                    <Box sx={{ borderBottom: "1px solid #CECECE" }}>
                      <ChatTabs
                        value={value}
                        onChange={handleChange}
                        aria-label="basic tabs example"
                        variant="scrollable"
                        scrollButtons="auto"
                      >
                        <ChatTabText label="Media" {...a11yProps(0)} />
                        <ChatTabText label="Inquiry" {...a11yProps(1)} />
                        <ChatTabText label="Quotation" {...a11yProps(2)} />
                      </ChatTabs>
                    </Box>
                    <CustomTabPanel value={value} index={0}>
                      <MediaTab />
                    </CustomTabPanel>
                    <CustomTabPanel value={value} index={1}>
                      Item Two
                    </CustomTabPanel>
                    <CustomTabPanel value={value} index={2}>
                      Item Three
                    </CustomTabPanel>
                  </Box>
                </OuterBoxTab>
              </ScrollDiv>
            </>
          ) : (
            <GroupInformationSection isAdminPage={true} />
          )}
        </Drawer>

        <Main open={open} sx={{ marginRight: open ? "390px" : 0 }}>
          <FullWebChatOuter>
            {/* <ProfileHeader text={""} /> */}
            <Grid container sx={{ height: "100%" }}>
              <Grid item xs={3} sm={2.6} md={2.6}>
                <UserList isAdmin={true} />
                {/* <EmptyUserList>
                  <EmptyBigChatRoomLeft>
                    <OuterChatContainer>
                      <EmptySellerIcon>
                        <i className="icon-livechat" style={{ fontSize: "40px" }}>
                          <span className="path1"></span>
                          <span className="path2"></span>
                        </i>
                      </EmptySellerIcon>
                      <Box>
                        <BoldHeadings>No Chat List Here</BoldHeadings>
                      </Box>
                    </OuterChatContainer>
                  </EmptyBigChatRoomLeft>
                </EmptyUserList> */}
              </Grid>
              <Grid
                item
                xs={9}
                sm={9.4}
                md={9.4}
                sx={{ borderLeft: "1px solid #ddd" }}
              >
                <RightSideChatSection>
                  <ChatRoom isAdmin={true} handleDraw={handleDrawerOpen} />
                  {/* <EmptyBigChatRoomRight>
                    <OuterChatContainer>
                      <Box>
                        <BoldHeadings>Add Seller To Start Chat</BoldHeadings>
                      </Box>
                      <Box>
                        <SubText>
                          Start a chat by adding seller by showing interest in the particular <br /> product to find new opporunities
                        </SubText>
                      </Box>
                      <EmptySellerImage>
                        <img src="/assets/chat/seller-emptyimage.svg" alt="" />
                      </EmptySellerImage>
                      <Box>
                        <BoldHeadings>
                          No Messages Yet
                        </BoldHeadings>
                      </Box>
                      <Box>
                        <SubText>
                          Looks like you haven't initiated a conversation with <br />any of our sellers
                        </SubText>
                      </Box>
                    </OuterChatContainer>
                  </EmptyBigChatRoomRight> */}
                </RightSideChatSection>
              </Grid>
            </Grid>
          </FullWebChatOuter>
        </Main>
      </div>
    </>
  );
}

export default ChatAdmin;
