import React, { useState, useEffect, useRef, useContext } from "react";
import logo from "./assets/images/logo.png";
import { BookIcon } from "./assets/svg/book";
import { SettingIcon } from "./assets/svg/setting";
import { SearchIcon } from "./assets/svg/search";
import {
  NotificationEmptyIcon,
  NotificationIcon,
} from "./assets/svg/notification";
import { ArrowDownIcon } from "./assets/svg/arrow-down";
import AccountDropdown from "./account-dropdown";
import avatar from "./assets/images/avatar.png";
import { Navbar, NavGroup, Nav, UserProfile } from "./index.styled";
import useHeader from "./getHeaderDetails";
import { FullPageLoader, OutletContext } from "..";
import { useLocation } from "react-router-dom";
import usFlag from "../../assets/images/usFlag.png";
import LanguageDropdown from "./languageDropdown";
import { getCookie } from "./getCookies";
// import { data } from "../GraphMap/data";
import { languagesData, selectedLanguageData } from "./languages";
import { QuestionMark } from "./assets/svg/questionMark";
import Learn from "../../assets/svg/learning";
import CommunityIcon from "../sideNav/svg/commIcon";
import DuetIcon from "../sideNav/svg/duetIcon";
import SpeechIcon from "../sideNav/svg/speechIcon";
import DictionaryIcon from "../sideNav/svg/dictionaryIcon";
import FunIcon from "../sideNav/svg/fun";
import CompuetrerIcon from "./assets/svg/computerIcon";

/**
 * @param {{
 *  type: string,
 *  text: string,
 *  onClick: Function,
 *  style: CSSProperties,
 * }} props - properties of Header Component
 *
 */
import useTranslation from "../../hooks/useTranslation.jsx";
import wordStore from "../../mc/wordStore.json";
const HeaderComponent = (props) => {
  const { findText } = useTranslation(wordStore);
  const [personalAccountData, setPersonalAccountData] = useState([]);
  const [developerAccountData, setDeveloperAccountData] = useState([]);
  const [instructorAccountData, setInstructorAccountData] = useState([]);
  const [enterpriseAccountData, setEnterpriseAccountData] = useState([]);
  const [languageDropdown, setLanguageDropdown] = useState();
  const [isOpen, setIsOpen] = useState(false);
  // const [searchResultOpen, setSearchResultOpen] = useState(false);
  // in general data find user info and replace where user details is being used
  const {
    handleGetUserAccountsDetail,
    userAccountsDetail,
    // getDefaultAccount,
    // handleGetDefaultAccount,
    unreadNotificationData,
    handleGetUnreadNotification,
    generalNotificationCountData,
    handleGeneralNotificationCount,
    notificationData,
    handleGetNotification,
    handleUpdateUserAccount,
    unreadNotificationPersonalData,
    handleGetUnreadNotificationPersonal,
    handleGeneralNotificationCountPersonal,
    setDefaultAccount,
    handleSetDefaultAccount,
  } = useHeader();
  const {
    setGeneralData,
    generalData,
    notificationMarkReadData,
    accountName,
    userDetails,
  } = useContext(OutletContext);
  const [accountType, setAccountType] = useState("");
  const currentAccountType = props?.selectedAccount?.type
    ? props?.selectedAccount?.type?.toLowerCase()
    : userAccountsDetail?.data?.[0]?.type?.toLowerCase();
  useEffect(() => {
    if (currentAccountType) {
      setAccountType(currentAccountType);
    }
  }, [currentAccountType]);
  useEffect(() => {
    setIsOpen(false);
    handleGetUserAccountsDetail();
  }, []);
  useEffect(() => {
    if (accountType && accountType !== "personal") {
      handleGetUnreadNotification(accountType);
    }
    if (accountType && accountType === "personal") {
      handleGetUnreadNotificationPersonal();
    }
  }, [accountType]);

  // Merge the notification_count into the results data using find
  const allUserAccountsDetail =
    userAccountsDetail?.data?.results?.map((item) => {
      const detail = generalNotificationCountData?.data?.detail?.find(
        (detailItem) => detailItem?.account_id === item?.id,
      );
      return {
        ...item,
        notification_count: detail ? detail?.notification_count : 0,
      };
    }) || [];

  useEffect(() => {
    if (accountType && accountType !== "personal") {
      handleGeneralNotificationCount(accountType);
    }
    if (accountType && accountType === "personal") {
      handleGeneralNotificationCountPersonal();
    }
  }, [accountType]);

  useEffect(() => {
    if (userAccountsDetail?.data) {
      setGeneralData((generalData) => ({
        ...generalData,
        accounts: userAccountsDetail?.data,
        user: userDetails?.data,
        selectedAccount: props?.selectedAccount,
        defaultAccount: props?.getDefaultAccount?.data,
      }));
      const cookies = document.cookie;
      const cookieArray = cookies.split(";");
      let activeDeveloperAccount;
      for (let i = 0; i < cookieArray.length; i++) {
        const cookie = cookieArray[i].trim();
        if (cookie.startsWith("defaultAccountID=")) {
          activeDeveloperAccount = cookie.substring(
            "defaultAccountID=".length,
            cookie.length,
          );
          break;
        }
      }
      let personalArray = [];
      let developerArray = [];
      let instructorArray = [];
      let enterpriseArray = [];
      allUserAccountsDetail?.map((accountItem, idx) => {
        if (accountItem?.type === "PERSONAL") {
          personalArray.push(accountItem);
          setPersonalAccountData(personalArray);
        }
        if (accountItem?.type === "DEVELOPER") {
          developerArray.push(accountItem);
          setDeveloperAccountData(developerArray);
        }
        if (accountItem?.type === "INSTRUCTOR") {
          instructorArray.push(accountItem);
          setInstructorAccountData(instructorArray);
        }
        if (accountItem?.type === "ENTERPRISE") {
          enterpriseArray.push(accountItem);
          setEnterpriseAccountData(enterpriseArray);
        }
      });
    }
  }, [
    userAccountsDetail?.data,
    generalNotificationCountData?.response,
    props?.getDefaultAccount?.response,
  ]);

  // update general data when selected acct changes

  useEffect(() => {
    if (props?.selectedAccount?.id) {
      setGeneralData((generalData) => ({
        ...generalData,
        selectedAccount: props?.selectedAccount,
      }));
    }
  }, [props?.selectedAccount]);

  // Checking for delete account
  // useEffect(() => {
  //   if (userAccountsDetail?.data) {
  //     // Filter for only valid accounts
  //     const validAccounts = userAccountsDetail.data?.results.filter(
  //       (account) => !account.pending_delete,
  //     );
  //     if (
  //       generalData?.selectedAccount &&
  //       generalData?.selectedAccount?.pending_delete
  //     ) {
  //       const nextValidAccount = validAccounts[0];
  //       if (nextValidAccount) {
  //         props?.setSelectedAccount(nextValidAccount);
  //       }
  //     }
  //   }
  // }, [generalData?.selectedAccount, userAccountsDetail?.data]);

  const [hasDeveloperAccount, setHasDeveloperAccount] = useState(false);
  // New useEffect to check for a DEVELOPER account
  useEffect(() => {
    if (userAccountsDetail?.data) {
      const hasDeveloper = userAccountsDetail.data.results.some(
        (account) => account.type === "DEVELOPER",
      );
      setHasDeveloperAccount(hasDeveloper);
    }
  }, [userAccountsDetail?.data]);
  const containerRef = useRef(null);
  const secondContainerRef = useRef(null);
  const acctDropdownContainerRef = useRef(null);

  // logic for closing language dropdown when clicking outside

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target)
      ) {
        setLanguageDropdown();
      }
    };
    document.addEventListener("click", handleClickOutside);
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [setLanguageDropdown]);

  // logic for closing accounts dropdown when clicking outside

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        secondContainerRef.current &&
        acctDropdownContainerRef.current &&
        !secondContainerRef.current.contains(event.target) &&
        !acctDropdownContainerRef.current.contains(event.target)
      ) {
        setIsOpen();
      }
    };
    document.addEventListener("click", handleClickOutside);
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [setIsOpen]);

  // Determine home page for active style purpose
  const isHomePage = () =>
    window.location.pathname === "/" ||
    window.location.pathname.includes("developer");

  // Determine the label based on the current path
  const hostname = window.location.hostname;
  const getNavLinkLabel = () => {
    const path = window.location.pathname;
    if (path.includes("fun")) return "Fun";
    if (path.includes("community")) return "Community";
    if (path.includes("explore")) return "Explore";
    if (path.includes("connect")) return "Connect";
    if (path.includes("dictionary")) return "Dictionary";
    if (hostname.includes("demo")) return "Demo";
    return "Learning";
  };
  const getNavLinkIcon = () => {
    const path = window.location.pathname;
    const hostname = window.location.hostname;
    if (path.includes("fun")) return <FunIcon width={23} height={23} />;
    if (path.includes("community"))
      return <CommunityIcon width={23} height={23} />;
    if (path.includes("explore")) return <DuetIcon width={23} height={23} />;
    if (path.includes("connect")) return <SpeechIcon width={23} height={23} />;
    if (path.includes("dictionary"))
      return <DictionaryIcon width={23} height={23} />;
    if (hostname.includes("demo")) return <CompuetrerIcon />;
    return <BookIcon width={23} height={23} />;
  };

  // websocket for notifications initialization
  const socketUrl = `${
    window.location.hostname.includes("localhost") ||
    window.location.hostname.includes("staging")
      ? "dev-117782726-api"
      : "api"
  }.learngual.com/notify/v1/ws/connect/`;

  // base url for help center
  const helpUrl = `${
    window.location.hostname.includes("localhost") ||
    window.location.hostname.includes("staging")
      ? "https://staging-help.learngual.com"
      : "https://help.learngual.com"
  }`;

  // base url
  const base = `${
    window.location.hostname.includes("localhost") ||
    window.location.hostname.includes("staging")
      ? `https://559staging.learngual.${
          window.location.hostname.includes(".ca") ? "ca" : "com"
        }`
      : `https://www.learngual.${
          window.location.hostname.includes(".ca") ? "ca" : "com"
        }`
  }`;
  const token = getCookie("access");
  const defaultAcctId = getCookie("defaultAccountID");
  const account_id = generalData?.defaultAccount?.id || defaultAcctId;

  // websocket for all notification account
  useEffect(() => {
    const websocket = new WebSocket(
      `wss://${socketUrl}?_account=${account_id}&authorization=${token}`,
    );
    const handler = (event) => {
      if (event?.data) {
        const data = JSON.parse(event?.data); //check for incoming message from socket
        if (data.event === "new.notification.result") {
          if (data.data) {
            props.setNewNotifications((prev) => [...prev, data.data]);
            if (accountType) {
              if (accountType === "personal") {
                handleGetUnreadNotificationPersonal();
                handleGeneralNotificationCountPersonal();
              } else {
                handleGetUnreadNotification(accountType);
                handleGeneralNotificationCount(accountType);
                handleGetNotification(accountType);
              }
            }
          }
        }
      }
    };
    websocket.addEventListener("message", handler, {
      passive: true,
    });
    return () => {
      websocket.removeEventListener("message", handler);
    };
  }, [accountType]);

  // websocket for room
  useEffect(() => {
    const websocket2 = new WebSocket(
      `wss://${socketUrl}?_account=${account_id}&authorization=${token}&room_id=${account_id}`,
    );
    const handler = (event) => {
      if (event?.data) {
        const data = JSON.parse(event?.data); //check for incoming message from socket
        if (data.event?.includes("notification")) {
          console.log("step1");

          if (data.data) {
            console.log("step2");

            if (accountType) {
              console.log(accountType, "ACCOUNT TYPE");
              if (accountType === "personal") {
                console.log("step3");

                handleGetUnreadNotificationPersonal();
              } else {
                handleGetUnreadNotification(accountType);
              }
            }
          }
        }
        if (data.event === "message.new") {
        }
        if (data.event === "new.room.result") {
          if (data.status) {
            if (accountType) {
              if (accountType === "personal") {
                handleGetUnreadNotificationPersonal();
                handleGeneralNotificationCountPersonal();
              } else {
                handleGetUnreadNotification(accountType);
                handleGeneralNotificationCount(accountType);
                handleGetNotification(accountType);
              }
            }
          }
        }
      }
    };
    websocket2.addEventListener("message", handler, {
      passive: true,
    });
    return () => {
      websocket2.removeEventListener("message", handler);
    };
  }, [accountType]);

  useEffect(() => {
    if (accountType) {
      if (accountType === "personal") {
        handleGetUnreadNotificationPersonal();
        handleGeneralNotificationCountPersonal();
      } else {
        handleGetUnreadNotification(accountType);
        handleGeneralNotificationCount(accountType);
      }
    }
  }, [notificationMarkReadData?.response, accountType]);
  const isPendingDelete =
    generalData?.selectedAccount?.pending_delete === true &&
    window.location.hostname.includes("staging");
  const value =
    props.defaultLang || localStorage.getItem("defaultLang") || "en";
  return (
    <Navbar>
      <a href={window.location.origin}>
        <img
          src={logo}
          alt={findText("Learngual logo")}
          style={{ width: 80 }}
        />
      </a>
      <Nav
        onClick={() => {
          setLanguageDropdown();
          setIsOpen();
        }}
      >
        <li>
          <a className={isHomePage() ? "active" : ""}>
            {getNavLinkIcon()} {props.findText(getNavLinkLabel())}
          </a>
        </li>

        <>
          <li>
            <a
              onClick={() => {
                window.location.href = `${base}/settings/account`;
              }}
              className={
                window.location.pathname.includes("settings") ? "active" : ""
              }
              style={{
                cursor: "pointer",
              }}
            >
              <SettingIcon /> {props.findText("Settings")}
            </a>
          </li>
          <li>
            <a
              onClick={(e) => {
                if (isPendingDelete) {
                  e.preventDefault();
                  e.stopPropagation();
                } else {
                  window.location.hostname.includes("coming")
                    ? (window.location.href = `https://www.learngual.com/auth/sign-in`)
                    : (window.location.href = `${base}/${props?.selectedAccount?.type ? props?.selectedAccount?.type?.toLowerCase() : userAccountsDetail?.data?.[0]?.type?.toLowerCase()}/notifications/`);
                }
              }}
              className={
                window.location.pathname.includes("notifications")
                  ? "active"
                  : isPendingDelete
                    ? "disabled"
                    : ""
              }
              style={{
                cursor: isPendingDelete ? "not-allowed" : "pointer",
              }}
            >
              {(
                accountType === "personal"
                  ? unreadNotificationPersonalData?.data?.count > 0
                  : unreadNotificationData?.data?.count > 0
              ) ? (
                <NotificationIcon />
              ) : (
                <NotificationEmptyIcon />
              )}
              {props.findText("Notifications")}
            </a>
          </li>
        </>
        <li
          style={{
            marginLeft: "20%",
            cursor: "pointer",
          }}
        >
          <a
            onClick={() => {
              window.location.href = helpUrl;
            }}
            className={
              window.location.pathname.includes("help") ? "active" : ""
            }
          >
            <QuestionMark /> {props?.findText("Help")}
          </a>
        </li>
      </Nav>
      {/* 
       <Help>
         <QuestionMark />
       Help
       </Help> */}

      <NavGroup
        onClick={() => {
          setLanguageDropdown();
          setIsOpen();
        }}
      >
        {/* {(!isDeveloper ||!window.location.hostname.includes("coming")) && ( // when developer and on staging, don't show
          <SearchInputGroup>
            <SearchIcon />
            <SearchInput
              type={props.inputType}
              value={props.value}
              id={props.inputId}
              placeholder={props.placeholder}
              style={props.inputStyles}
              onChange={props.onChange}
              onFocus={() => setSearchResultOpen(true)}
              onBlur={() => setSearchResultOpen(false)}
            />
             {searchResultOpen && (
              <div className="search-result-wrapper">
                <p></p>
              </div>
            )}
          </SearchInputGroup>
         )} */}

        <div className="language_dropdown" onClick={(e) => e.stopPropagation()}>
          <div
            className="drop_holder"
            onClick={() => {
              setLanguageDropdown(!languageDropdown);
              setIsOpen();
            }}
          >
            <img src={selectedLanguageData[value] || usFlag} alt="" />
            <ArrowDownIcon />
          </div>
          {languageDropdown && (
            <LanguageDropdown
              languageDropdown={languageDropdown}
              setLanguageDropdown={setLanguageDropdown}
              findText={props.findText}
              defaultLang={props.defaultLang}
              setDefaultLang={props.setDefaultLang}
              setIsTranslationsLoading={props.setIsTranslationsLoading}
            />
          )}
        </div>
        {props?.selectedAccount && (
          <UserProfile
            onClick={(e) => {
              e.stopPropagation();
              setIsOpen(!isOpen);
              setLanguageDropdown();
            }}
            ref={secondContainerRef}
          >
            <div className="user-img-container">
              <img
                src={props?.selectedAccount?.profile_photo?.url || avatar}
                alt={props?.findText("profile")}
              />
            </div>
            <div className="user-info-container">
              <h5
                style={{
                  textTransform: "capitalize",
                }}
              >
                {accountName}
              </h5>
              <h6
                style={{
                  textTransform: "capitalize",
                }}
              >
                {props?.selectedAccount?.type?.toLowerCase() === "personal"
                  ? props?.findText("Student")
                  : props
                      ?.findText(props?.selectedAccount?.type?.toUpperCase())
                      ?.toLowerCase()}
              </h6>
            </div>
            <ArrowDownIcon width={16} height={10} />
          </UserProfile>
        )}
      </NavGroup>

      <>
        {isOpen && (
          <AccountDropdown
            avatar={avatar}
            activeAccountName={props?.selectedAccount?.display_name}
            activeAccountType={findText("Personal Account")}
            accountName={findText("Default name")}
            accountType={findText("Default Account")}
            notificationCount={findText("5")}
            isOpen={isOpen}
            setIsOpen={setIsOpen}
            data={userAccountsDetail}
            selectedAccount={props?.selectedAccount}
            setSelectedAccount={props?.setSelectedAccount}
            developerAccountData={developerAccountData}
            setDeveloperAccountData={setDeveloperAccountData}
            personalAccountData={personalAccountData}
            setPersonalAccountData={setPersonalAccountData}
            instructorAccountData={instructorAccountData}
            setInstructorAccountData={setInstructorAccountData}
            enterpriseAccountData={enterpriseAccountData}
            setEnterpriseAccountData={setEnterpriseAccountData}
            setGeneralData={setGeneralData}
            userAccountsDetail={userAccountsDetail}
            userDetails={userDetails}
            setDefaultAccount={setDefaultAccount}
            handleSetDefaultAccount={handleSetDefaultAccount}
            ref={acctDropdownContainerRef}
            hasDeveloperAccount={hasDeveloperAccount}
            findText={props.findText}
          />
        )}
      </>
    </Navbar>
  );
};
export default HeaderComponent;
