import React, { useState, useEffect, useContext } from "react";
import PropTypes from "prop-types";
import {
  SideMenuContainer,
  NavigationItemContainer,
  IconContainer,
  TextContainer,
  NotificationCount,
  LogoutButtonContainer,
  NavigationContainer,
} from "./styles";
import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";
import UserCard from "../userCard";
import cx from "classnames";
import InstructorRightBar from "../../fileRightBar/instructorRightBar";
import EnterpriseRightBar from "../../fileRightBar/enterpriseRightBar";
import { OutletContext } from "../../AppMainLayout";
import useTranslation from "../../../hooks/useTranslation.jsx";
import wordStore from "../../../mc/wordStore.json";
const SideMenu = ({
  user,
  routes,
  userType,
  onLogout = () => {},
  isOpen,
  setIsOpen,
  affiliatesActive,
  setRightComponent,
  planState,
  findText,
}) => {
  //console.log("user type", userType);
  // const [isOpen, setIsOpen] = useState(false);
  const [gracePeriod, setGracePeriod] = useState(true);
  const { setGeneralData, generalData, messageKit } = useContext(OutletContext);
  const { state } = messageKit;
  const onToggle = () => {
    setIsOpen(!isOpen);
    window.localStorage.setItem("isOpen", !isOpen);
  };
  useEffect(() => {
    setGeneralData({
      ...generalData,
      isOpen,
    });
  }, [isOpen]);

  // Normal route filter
  const [filteredRoutes, setFilteredRoutes] = useState();

  // When personal and on staging
  const isPersonal =
    generalData?.selectedAccount?.type === "PERSONAL" &&
    window.location.hostname.includes("staging");

  // When pending delete and on staging
  const isPendingDelete = generalData?.selectedAccount?.pending_delete === true;
  useEffect(() => {
    if (userType) {
      setFilteredRoutes(
        routes.find((route) => route.userType === userType)?.routes,
      );
    }
  }, [userType]);
  const [routeFilter, setRouteFilter] = useState();
  useEffect(() => {
    setRouteFilter(filteredRoutes);
  }, []);

  // filter route to remove contract
  const affiliatesFilteredRoute = filteredRoutes?.filter(
    (route) => !route.affiliates,
  );

  //console.log("filteredRoutes", routeFilter, affiliatesActive);
  useEffect(() => {
    if (!affiliatesActive) {
      setRouteFilter(affiliatesFilteredRoute);
    } else {
      setRouteFilter(filteredRoutes);
    }
  }, [affiliatesActive, filteredRoutes]);

  // Right bars
  // const EnterpriseRight = <EnterpriseRightBar />;
  // const InstructorRight = <InstructorRightBar />;

  const renderNavigationItem = (route, index) => {
    let notificationCount;
    const { icon, iconActive, text, notifications, path, affiliates, newTab } =
      route;
    const handlePathCheck = () => {
      let statusText;
      //console.log(window.location.pathname, "pathname");
      // checking developer account routes
      if (
        (window.location.pathname.includes("api") && path === "/developer") ||
        (window.location.pathname === "/developer" && path === "/developer")
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("documentation") &&
        path === "/developer/documentation"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("developer/report") &&
        path === "/developer/report"
      ) {
        return (statusText = true);
      }

      // checking personal account routes
      if (
        window.location.pathname.includes("/personal/dashboard") &&
        path === "/personal/dashboard"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/personal/library") &&
        path === "/personal/library"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/personal/courses") &&
        path === "/personal/courses"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/personal/reports") &&
        path === "/personal/reports"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/msg/personal/messages") &&
        path === "/msg/personal/messages"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/personal/addons") &&
        path === "/personal/addons"
      ) {
        return (statusText = true);
      }

      // checking enterprise account routes

      if (
        window.location.pathname.includes("/enterprise/dashboard") &&
        path === "/enterprise/dashboard"
      ) {
        // setRightComponent(EnterpriseRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/enterprise/courses") &&
        path === "/enterprise/courses"
      ) {
        // setRightComponent(EnterpriseRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/enterprise/reports") &&
        path === "/enterprise/reports"
      ) {
        // setRightComponent(EnterpriseRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/enterprise/manage-teams") &&
        path === "/enterprise/manage-teams"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/msg/enterprise/messages") &&
        path === "/msg/enterprise/messages"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/enterprise/announcements") &&
        path === "/enterprise/announcements"
      ) {
        // setRightComponent(EnterpriseRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/enterprise/analytics") &&
        path === "/enterprise/analytics"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/enterprise/file-manager") &&
        path === "/enterprise/file-manager"
      ) {
        return (statusText = true);
      }

      // checking instructor account routes

      if (
        window.location.pathname.includes("/instructor/dashboard") &&
        path === "/instructor/dashboard"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/courses") &&
        path === "/instructor/courses"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/reports") &&
        path === "/instructor/reports"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/manage-teams") &&
        path === "/instructor/manage-teams"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/analytics") &&
        path === "/instructor/analytics"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/manage-students") &&
        path === "/instructor/manage-students"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/msg/instructor/messages") &&
        path === "/msg/instructor/messages"
      ) {
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/contracts") &&
        path === "/instructor/contracts"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/announcements") &&
        path === "/instructor/announcements"
      ) {
        // setRightComponent(InstructorRight)
        return (statusText = true);
      }
      if (
        window.location.pathname.includes("/instructor/file-manager") &&
        path === "/instructor/file-manager"
      ) {
        return (statusText = true);
      } else {
        return (statusText = false);
      }
    };
    const active = handlePathCheck();
    if (notifications && String(text).toLowerCase().includes("message")) {
      notificationCount = (state?.roomsByCourses || []).reduce((acc, group) => {
        const groupCount =
          group?.total_unread_count ?? group?.unread_count ?? null;

        if (groupCount !== null) {
          const numericGroupCount = Number(groupCount);
          return (
            acc + (Number.isFinite(numericGroupCount) ? numericGroupCount : 0)
          );
        }

        const roomsCount = (group?.rooms || []).reduce((roomAcc, room) => {
          const numericRoomCount = Number(room?.unread_count ?? 0);
          return (
            roomAcc + (Number.isFinite(numericRoomCount) ? numericRoomCount : 0)
          );
        }, 0);

        return acc + roomsCount;
      }, 0);
    }
    console.log(notifications, notificationCount, "NOQ");

    return (
      <NavigationItemContainer
        onClick={() => {
          if (newTab) {
            window.open(path, "_blank");
          } else {
            window.location.href = `${path}`;
          }
        }}
        key={index}
        className={cx({
          active,
          [route.text]: true,
          disabled: route.disabled || isPendingDelete,
          pending_delete_item: isPendingDelete,
        })}
        minimal={isOpen}
      >
        <IconContainer active={active}>
          {active ? iconActive : icon}
        </IconContainer>
        <TextContainer minimal={isOpen}>{findText(text)}</TextContainer>

        {!!notifications && (
          <NotificationCount
            minimal={isOpen}
            className={cx({
              pending_delete_item: isPendingDelete,
            })}
          >
            <div className="text">
              {notificationCount ? notificationCount : 0}
            </div>
          </NotificationCount>
        )}
      </NavigationItemContainer>
    );
  };
  return (
    <SideMenuContainer
      isOpen={isOpen}
      className={
        isPendingDelete
          ? "pending_delete"
          : planState === "EXPIRED" &&
              generalData?.selectedAccount?.type?.toLowerCase() === "enterprise"
            ? "grace_period disabled"
            : ""
      }
    >
      <UserCard user={user} isOpen={isOpen} findText={findText} />
      <NavigationContainer>
        {routeFilter && routeFilter?.map(renderNavigationItem)}
      </NavigationContainer>
      <LogoutButtonContainer onClick={onLogout}>
        <IconContainer>{/* <CiLogout /> */}</IconContainer>
        {/* <TextContainer minimal={isOpen}>Log out</TextContainer> */}
      </LogoutButtonContainer>
      <div
        className="toggle"
        onClick={onToggle}
        style={{
          cursor: "pointer",
        }}
      >
        {isOpen ? <IoIosArrowBack /> : <IoIosArrowForward />}
      </div>
    </SideMenuContainer>
  );
};
SideMenu.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string.isRequired,
    handle: PropTypes.string.isRequired,
    avatar: PropTypes.string.isRequired,
  }).isRequired,
  routes: PropTypes.arrayOf(
    PropTypes.shape({
      userType: PropTypes.string.isRequired,
      routes: PropTypes.arrayOf(
        PropTypes.shape({
          path: PropTypes.string.isRequired,
          icon: PropTypes.element.isRequired,
          text: PropTypes.string.isRequired,
          notifications: PropTypes.number,
          disabled: PropTypes.bool,
        }),
      ).isRequired,
    }),
  ).isRequired,
  onLogout: PropTypes.func,
};
export default SideMenu;
