import React, { useState, useEffect, useRef, useCallback } from "react";
import logo from "./assets/images/logo.png";
import { Navbar2, NavGroup2 } from "./index.styled";
import { ArrowDownIcon } from "./assets/svg/arrow-down";
import ButtonComponent from "../button";
import { useLocation, useNavigate } from "react-router-dom";
import { languagesData, selectedLanguageData } from "./languages";
import { LanguageDropdownContainer } from "./index.styled";
import { InputSearchIcon } from "./assets/svg/search";
import { CloseIcon } from "./assets/svg/close";
import DebounceInput from "react-debounce-input";
import useHeader from "./getHeaderDetails";
import { getCookie } from "./getCookies";

/**
 * @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 HeaderComponentTwo = (props) => {
  const {
    findText: fallbackFindText,
    defaultLang: fallbackDefaultLang,
    setDefaultLang: fallbackSetDefaultLang,
    setIsTranslationsLoading: fallbackSetIsTranslationsLoading,
  } = useTranslation(wordStore);
  const [isOpen, setIsOpen] = useState(false);
  const [languageDropdown, setLanguageDropdown] = useState();
  const [filteredData, setFilteredData] = useState([]);
  const [isSearch, setIsSearch] = useState(false);
  const findText = props.findText || fallbackFindText;
  const currentLang = props.defaultLang || fallbackDefaultLang;
  const setCurrentLang = props.setDefaultLang || fallbackSetDefaultLang;
  const setCurrentTranslationsLoading =
    props.setIsTranslationsLoading || fallbackSetIsTranslationsLoading;
  const value = currentLang || localStorage.getItem("defaultLang") || "en";
  const { handleUpdateUserAccount } = useHeader();
  const navigate = useNavigate();
  useEffect(() => {
    setIsOpen(false);
  }, []);
  const goToLogin = useCallback(() => {
    navigate("/sign-in");
  }, []);
  console.log("testlog");

  const handleFilter = (event) => {
    const searchWord = event.target.value;
    const newFilter = languagesData.filter((item) =>
      item?.name?.toLowerCase().includes(searchWord.toLowerCase()),
    );
    if (searchWord === "") {
      setFilteredData([]);
      setIsSearch(false);
    } else {
      setFilteredData(newFilter);
      setIsSearch(true);
    }
  };

  // logic for closing language dropdown when clicking outside

  const containerRef = useRef(null);
  const handleLogoClick = () => {
    window.location.href = "/";
  };

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

  const handleLanguageChange = async (item) => {
    const selectedLanguage = item?.slug;

    setLanguageDropdown();
    selectedLanguage === currentLang
      ? setCurrentTranslationsLoading(false)
      : setCurrentTranslationsLoading(true);

    const accessToken = getCookie("access");
    const defaultAccountID = getCookie("defaultAccountID");

    if (accessToken && defaultAccountID) {
      try {
        await handleUpdateUserAccount(defaultAccountID, {
          language: selectedLanguage,
        });
      } catch (error) {
        console.error("Failed to update account language:", error);
      }
    }

    setCurrentLang(selectedLanguage);
  };
  const displayList = isSearch ? filteredData : languagesData;

  return (
    <Navbar2
      onClick={() => {
        setLanguageDropdown();
      }}
    >
      <img
        src={logo}
        alt={findText("Learngual logo")}
        onClick={handleLogoClick}
      />
      {/* <Nav2>
        <li>
          <a href="#" className="active">
            What we do
          </a>
        </li>
        <li>
          <a href="#">Demo</a>
        </li>
        <li>
          <a href="#">Pricing</a>
        </li>
        <li>
          <a href="#">Contact</a>
        </li>
       </Nav2> */}

      <NavGroup2>
        <div className="language_dropdown" onClick={(e) => e.stopPropagation()}>
          <div
            className="drop_holder"
            onClick={() => setLanguageDropdown(!languageDropdown)}
          >
            <img
              src={
                selectedLanguageData[value] || "https://flagcdn.com/w40/us.png"
              }
              alt=""
            />
            <ArrowDownIcon />
          </div>
          {languageDropdown && (
            <LanguageDropdownContainer ref={containerRef}>
              <div className="ldc_header">
                <p className="ldc_title">{findText("What's your language?")}</p>
                <span onClick={() => setLanguageDropdown(false)}>
                  <CloseIcon width={20} height={20} />
                </span>
              </div>
              <div className="ldc_search">
                <span>
                  <InputSearchIcon />
                </span>
                <DebounceInput
                  type="text"
                  debounceTimeout={500}
                  onChange={handleFilter}
                  className="search_input"
                  placeholder={findText("Search")}
                />
              </div>
              <div className="language_dropdown_list">
                {displayList?.map((item, idx) => (
                  <div
                    key={idx}
                    className="language_dropdown_item"
                    onClick={() => handleLanguageChange(item)}
                  >
                    <img src={item?.flag} alt={item?.name} />
                    <span>{item?.name}</span>
                  </div>
                ))}
              </div>
            </LanguageDropdownContainer>
          )}
        </div>

        {window.location.pathname.includes("sign-up") &&
          !window.location.pathname.includes("organization-details") &&
          !window.location.pathname.includes("subscription-plan") &&
          !window.location.pathname.includes("payment") && (
            <ButtonComponent
              type="secondary"
              text={(props?.findText || findText)("Sign in")}
              onClick={goToLogin}
            />
          )}
      </NavGroup2>
    </Navbar2>
  );
};
export default HeaderComponentTwo;
