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

interface GroupByPopUpProps {
  selectedGroups: { label: string; value: string }[];
  groupableFields: { label: string; value: string }[];
  onPopupToggle: () => void;
  onGroupApply: (groupField: { label: string; value: string }[]) => void;
}

const GroupByPopUp = (props: GroupByPopUpProps) => {
  const [groupFields, setGroupFields] = useState(props.selectedGroups);

  useEffect(() => {
    setGroupFields(props.selectedGroups);
  }, []);

  const isDirty = !_.isEqual(groupFields, props.selectedGroups);

  const onGroupChange = (
    _callBack: any,
    _fieldName: any,
    value: any,
  ) => {
    const grouped = _.groupBy(value, "value");
    const duplicateValues = Object.values(grouped)
      .filter((group) => group.length > 1)
      .flat();
    const groups = value.filter(
      (f: any) => !duplicateValues.some((d: any) => d.value === f.value),
    );
    setGroupFields(groups);
  };

  return (
    <div className="tmpl-group-filter-popup">
      <div className="tmpl-group-filter-popup-header">
        <div>
          <h2>Select a new group</h2>
          <p>
            This option would allow you to select from existing set of pre-built
            groups
          </p>
        </div>
        <FactoryRenderer
          onClick={props.onPopupToggle}
          widgetStyle={{ className: "qo-btn qo-text-default tmpl-button" }}
          name="close"
          uiElementType="WIDGET"
          fillMode="clear"
          widgetType="ICON"
          title=""
        />
      </div>
      <div className="tmpl-group-filter-popup-body">
        <div className="tmpl-dropdown-container">
          <span>Group By</span>
          <FactoryRenderer
            uiElementType="WIDGET"
            widgetType="MULTISELECT"
            onChange={onGroupChange}
            textField="label"
            dataItemKey="value"
            listData={props.groupableFields}
            widgetStyle={{ className: "tmpl-dropdown" }}
            value={groupFields}
            placeholder="Select Group"
          />
        </div>
        <div className="tmpl-group-filter-popup-footer">
          <FactoryRenderer
            onClick={() => props.onGroupApply(groupFields)}
            widgetStyle={{ className: "qo-btn qo-btn-primary qo-text-light" }}
            uiElementType="WIDGET"
            widgetType="BUTTON"
            disabled={!isDirty}
            title="Save And Continue"
          />
        </div>
      </div>
    </div>
  );
};
export default GroupByPopUp;
