/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useEffect, useRef } from "react";
import AdvancedSearchView from "./AdvancedSearchView";
import FilterPopup from "./FilterPopup";
import { FilterTarget } from "../../data/advancedSearch";
import { useFilterData } from "./helper/useFilterData";

type AdvancedSearchProps = {
  visible: boolean;
  disabled: boolean;
  enableCustomView?: boolean;
  filterableFields: FilterTarget[];
  uiElementGroupData: Record<string, any>;
  config: { uiElementGroupId: string };
  onModelUpdate: (
    callBack: ((args: any) => void) | null,
    fieldName: string,
    value: any,
  ) => void;
  loadTemplateSupportiveData?: (
    callBack: (args: any) => void,
    supportiveKeys: any,
  ) => Promise<any>;
};

const AdvancedSearch: React.FC<AdvancedSearchProps> = (props) => {
  const { loadSupportiveData, cache } = useFilterData({
    loadTemplateSupportiveData: props.loadTemplateSupportiveData,
  });
  const [togglePopup, setTogglePopup] = useState(false);
  const popupRef = useRef<HTMLDivElement>(null);

  const handlePopupShow = () => {
    setTogglePopup(!togglePopup);
  };

  const handleClickOutside = (event: MouseEvent) => {
    const target = event.target as HTMLElement;
    const isInsideMyPopup = target.closest(`.tmpl-prvent-outside-click-close`);

    if (
      popupRef.current &&
      !popupRef.current.contains(event.target as Node) &&
      !isInsideMyPopup
    ) {
      setTogglePopup(false);
    }
  };

  useEffect(() => {
    if (togglePopup) {
      document.addEventListener("mousedown", handleClickOutside);
    } else {
      document.removeEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [togglePopup]);

  return props.visible ? (
    <div className="tmpl-advanced-search-container" ref={popupRef}>
      <AdvancedSearchView
        handlePopupShow={handlePopupShow}
        disabled={props.disabled}
        hasAppliedFilter={
          props.enableCustomView &&
          (props.uiElementGroupData?.advancedSearch?.appliedQuery?.filters?.length > 0)
        }
      />
      {togglePopup && !props.disabled && (
        <div
          className="tmpl-advanced-popup"
          onClick={(e) => e.stopPropagation()}
        >
          <FilterPopup
            uiElementGroupData={props.uiElementGroupData}
            filterableFields={props.filterableFields}
            config={props.config}
            onModelUpdate={props.onModelUpdate}
            handlePopupShow={handlePopupShow}
            loadSupportiveData={loadSupportiveData}
            cache={cache}
          />
        </div>
      )}
    </div>
  ) : (
    <></>
  );
};

export default AdvancedSearch;
