/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useMemo, useRef, useState } from "react";
import SettingView from "./SettingView";
import ColumnChooser from "./ColumnChooser/ColumnChooser";

import SettingPopup from "./SettingPopup";
import { ChooserColumn } from "../../data/setting";
import _ from "lodash";

export enum DataWidgetType {
  CARD = "CARD",
  GRID = "GRID",
}

export type SettingProps = {
  visible: boolean;
  disabled: boolean;
  disableColumnChooser: boolean;
  disabledDisplayWidgetType: boolean;
  enableCustomView?: boolean;
  defaultActiveDataWidgetType?: DataWidgetType;
  columns: ChooserColumn[];
  uiElementGroupData: Record<string, any>;
  config: { uiElementGroupId: string };
  onModelUpdate: (
    callBack: ((args: any) => void) | null,
    fieldName: string,
    value: any,
  ) => void;
};

const Setting = (props: SettingProps) => {
  const [togglePopup, setTogglePopup] = useState(false);
  const [toggleColumnChooser, setToggleColumnChooser] = 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)) {
      setTogglePopup(false);
    }
  };

  const onSettingClick = () => {
    setTogglePopup((prevToggle) => !prevToggle);
  };

  const onChooserClick = () => {
    setToggleColumnChooser(
      (prevToggleColumnChooser) => !prevToggleColumnChooser,
    );
    setTogglePopup(false);
  };

  const hasSettingChanged = useMemo(() => {
    if (!props.enableCustomView) return false;
    const currentSetting = props.uiElementGroupData?.setting;
    if (!currentSetting) return false;

    const appliedColumns = currentSetting?.columnChooser?.appliedColumns;
    const defaultSelectedColumns = props.columns
      ?.filter((c: ChooserColumn) => c.selected)
      ?.sort(
        (a: ChooserColumn, b: ChooserColumn) => (a.order ?? 0) - (b.order ?? 0),
      );
    const columnsChanged =
      appliedColumns &&
      defaultSelectedColumns?.length &&
      !_.isEqual(appliedColumns, defaultSelectedColumns);

    const widgetTypeChanged =
      currentSetting?.activeDataWidgetType &&
      props.defaultActiveDataWidgetType &&
      currentSetting.activeDataWidgetType !== props.defaultActiveDataWidgetType;

    return !!(columnsChanged || widgetTypeChanged);
  }, [
    props.enableCustomView,
    props.defaultActiveDataWidgetType,
    props.columns,
    props.uiElementGroupData?.setting,
  ]);

  const onWidgetTypeClick = () => {
    setTogglePopup(false);
    const updatedSetting = {
      ...props.uiElementGroupData?.setting,
      activeDataWidgetType:
        props.uiElementGroupData?.setting?.activeDataWidgetType ===
        DataWidgetType.GRID
          ? DataWidgetType.CARD
          : DataWidgetType.GRID,
    };

    const updatedUiElementGroupData = {
      ...props.uiElementGroupData,
      setting: updatedSetting,
    };

    props.onModelUpdate(
      null,
      props.config.uiElementGroupId,
      updatedUiElementGroupData,
    );
    setTogglePopup(false);
  };

  return props.visible ? (
    <div className="tmpl-setting-container" ref={popupRef}>
      <SettingView
        disabled={props.disabled}
        onSettingClick={onSettingClick}
        hasAppliedFilter={hasSettingChanged}
      />
      {togglePopup && !props.disabled && (
        <SettingPopup
          activeDataWidgetType={
            props.uiElementGroupData?.setting?.activeDataWidgetType
          }
          onSettingClick={onSettingClick}
          onChooserClick={onChooserClick}
          onWidgetTypeClick={onWidgetTypeClick}
        />
      )}
      {toggleColumnChooser && !props.disabled && (
        <ColumnChooser
          uiElementGroupData={props.uiElementGroupData}
          toggleColumnChooser={toggleColumnChooser}
          columns={props.columns}
          config={props.config}
          onChooserClick={onChooserClick}
          onModelUpdate={props.onModelUpdate}
          setToggleColumnChooser={setToggleColumnChooser}
          setTogglePopup={setTogglePopup}
        />
      )}
    </div>
  ) : (
    <></>
  );
};
export default Setting;
