import React, { useState, useEffect, useRef, useContext } from "react";
import useHeader from "./getHeaderDetails";
import { OutletContext } from "..";
import { LanguageDropdownContainer } from "./index.styled";
import { RiCloseCircleFill } from "react-icons/ri";
import { InputSearchIcon } from "./assets/svg/search";
import DebounceInput from "react-debounce-input";
import { languagesData } from "./languages";

/**
 * @param {{
 *  type: string,
 *  text: string,
 *  onClick: Function,
 *  style: CSSProperties,
 * }} props - properties of Language dropdown Component
 *
 */

const LanguageDropdown = ({
  languageDropdown,
  setLanguageDropdown,
  findText,
  defaultLang,
  setDefaultLang,
}) => {
  const { generalData } = useContext(OutletContext);
  const { handleUpdateUserAccount } = useHeader();
  const [filteredData, setFilteredData] = useState([]);
  const [isSearch, setIsSearch] = useState(false);
  const containerRef = useRef(null);

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

  // 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]);

  const handleLanguageChange = async (item) => {
    if (generalData?.defaultAccount?.id) {
      await handleUpdateUserAccount(generalData?.defaultAccount?.id, {
        language: item?.slug,
      });
    }
    setLanguageDropdown();
    setDefaultLang(item?.slug);
    window.location.reload();
  };

  const displayList = isSearch ? filteredData : languagesData;

  return (
    <LanguageDropdownContainer ref={containerRef}>
      <div className="ldc_header">
        <p className="ldc_title">{findText("What's your language?")}</p>
        <span onClick={() => setLanguageDropdown(false)}>
          <RiCloseCircleFill />
        </span>
      </div>

      <div className="ldc_search">
        <span>
          <InputSearchIcon />
        </span>
        <DebounceInput
          type="text"
          debounceTimeout={500}
          onChange={handleFilter}
          className="search_input"
          name=""
          id=""
          placeholder={findText("Search")}
        />
      </div>

      <div className="language_dropdown_list">
        {displayList?.map((item, index) => (
          <div
            key={index}
            className="language_dropdown_item"
            onClick={() => handleLanguageChange(item)}
          >
            <img src={item?.flag} alt={item?.name} />
            <span>{item?.name}</span>
          </div>
        ))}
      </div>
    </LanguageDropdownContainer>
  );
};
export default LanguageDropdown;
