/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef, useState } from "react";
import GroupByView from "./GroupByView";
import GroupByPopUp from "./GroupByPopUp";
import _ from "lodash";

export type GroupByProps = {
  visible: boolean;
  disabled: boolean;
  enableCustomView?: boolean;
  groupableFields: { label: string; value: string }[];
  uiElementGroupData: Record<string, any>;
  config: { uiElementGroupId: string };
  onModelUpdate: (
    callBack: ((args: any) => void) | null,
    fieldName: string,
    value: any
  ) => void;
};

const GroupBy = (props: GroupByProps) => {
  const [togglePopup, setTogglePopup] = useState(false);
  const popupRef = useRef<HTMLDivElement>(null);

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

  const handleClickOutside = (event: MouseEvent) => {
    if (
      popupRef.current &&
      !popupRef.current.contains(event.target as Node) &&
      (event.target as any)?.offsetParent?.className !== "k-list-content"
    ) {
      setTogglePopup(false);
    }
  };

  const onGroupApply = (groupFields: { label: string; value: string }[]) => {
    const updatedGroupedBy = {
      ...props.uiElementGroupData.groupedBy,
      appliedGroups: _.cloneDeep(groupFields),
    };

    const updatedUiElementGroupData = {
      ...props.uiElementGroupData,
      groupedBy: updatedGroupedBy,
    };
    setTogglePopup(false);
    props.onModelUpdate(
      null,
      props.config.uiElementGroupId,
      updatedUiElementGroupData
    );
  };

  const onPopupToggle = () => {
    setTogglePopup((prevToggle) => !prevToggle);
  };
  return props.visible ? (
    <div className="tmpl-group-filter-container" ref={popupRef}>
      <GroupByView
        disabled={props.disabled}
        onPopupToggle={onPopupToggle}
        hasAppliedFilter={
          props.enableCustomView &&
          (props.uiElementGroupData?.groupedBy?.appliedGroups?.length > 0)
        }
      />
      {togglePopup && !props.disabled && (
        <GroupByPopUp
          selectedGroups={
            props.uiElementGroupData?.groupedBy?.appliedGroups ?? []
          }
          groupableFields={props.groupableFields}
          onPopupToggle={onPopupToggle}
          onGroupApply={onGroupApply}
        />
      )}
    </div>
  ) : (
    <></>
  );
};
export default GroupBy;
