/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect } from "react";
import Filter from "./Filter";
import { FilterExpression } from "../../data/quickFilter";
import _ from "lodash";

interface FilterPopupProps {
  filterRows: FilterExpression[];
  uiElementGroupData: Record<string, any>;
  config: { uiElementGroupId: string };
  dataKeyRelatedValues?: Record<string, any[]>;
  onModelUpdate: (
    callBack: ((args: any) => void) | null,
    fieldName: string,
    value: any,
  ) => void;
  onQuickFilterApply: (
    id: string,
    value: { label: string; value: any },
  ) => void;
}

const FilterPopup = (props: FilterPopupProps) => {
  // If appliedQuery.filterRows has data but filterRows doesn't, populate filterRows from appliedQuery
  useEffect(() => {
    const quickFilter = _.cloneDeep(props.uiElementGroupData?.quickFilter);
    const hasAppliedFilterRows =
      quickFilter?.appliedQuery?.filterRows?.length > 0;
    let hasAppliedChanges = false;

    if (hasAppliedFilterRows) {
      quickFilter.appliedQuery.filterRows?.map(
        (appliedRow: FilterExpression) => {
          const matchedIndex = quickFilter?.filterRows?.findIndex(
            (row: FilterExpression) =>
              appliedRow.propertyToFilter.label === row.propertyToFilter.label,
          );
          if (
            matchedIndex > -1 &&
            !quickFilter.filterRows[matchedIndex].value
          ) {
            quickFilter.filterRows[matchedIndex].value = appliedRow.value;
            hasAppliedChanges = true;
          }
        },
      );

      if (hasAppliedChanges) {
        const updatedUiElementGroupData = {
          ...props.uiElementGroupData,
          quickFilter: quickFilter,
        };

        props.onModelUpdate(
          null,
          props.config.uiElementGroupId,
          updatedUiElementGroupData,
        );
      }
    }
  }, []);

  return (
    <div className="tmpl-quick-filter-popup">
      {props.filterRows?.map((filterRow) => (
        <Filter
          key={filterRow.id}
          filterRow={filterRow}
          onQuickFilterApply={props.onQuickFilterApply}
          dataKeyRelatedValues={props.dataKeyRelatedValues}
        />
      ))}
    </div>
  );
};
export default FilterPopup;
