/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState } from "react";
import FactoryRenderer from "../../../../Renderer";
import {
  FilterExpressionViewModel,
  FilterTarget,
} from "../../data/advancedSearch";
import { Operator } from "../../enum";
import Filter from "./Filter";
import { isFilterValueEmpty } from "./helper/AdvancedSearchFunctions";

interface FilterPopupViewProps {
  uiElementGroupId: string;
  filterRows: FilterExpressionViewModel[];
  criteria: string;
  cache?: Record<string, any[]>;
  loadSupportiveData: (propertyToFilter: FilterTarget) => Promise<void>;
  onFilterTargetChange: (value: FilterTarget, id: string) => void;
  onOperatorChange: (
    value: { label: string; value: Operator | null },
    id: string
  ) => void;
  onFilterValueChange: (value: any, id: string) => void;
  onCriteriaToggle: (id: string) => void;
  onAddFilter: (id: string) => void;
  onDeleteFilter: (id: string) => void;
  onClear: () => void;
  onCriteriaApplied: () => void;
  onCopyToClipboard: () => void;
  onCancel: () => void;
  onApply: () => void;
  isApplyDisabled?: boolean;
  isClearDisabled?: boolean;
}

const FilterPopupView = (props: FilterPopupViewProps) => {
  const [validationErrors, setValidationErrors] = useState<Set<string>>(
    new Set(),
  );

  const validateAndApply = () => {
    const errors = new Set<string>();
    props.filterRows.forEach((row) => {
      const hasFilter =
        row.selectedFilter?.propertyToFilter?.apiPropertyName;
      const hasOperator = row.selectedFilter?.operator?.value != null;
      const hasValue = !isFilterValueEmpty(row.selectedFilter?.value);

      if (!hasFilter || !hasOperator || !hasValue) {
        errors.add(row.id);
      }
    });

    if (errors.size > 0) {
      setValidationErrors(errors);
      return;
    }

    setValidationErrors(new Set());
    props.onApply();
  };

  return (
    <>
      <div className="tmpl-filter-container">
        <div className="tmpl-filter">
          <div className="tmpl-header-title">Filter</div>
          <div className="tmpl-header-title">Operator</div>
          <div className="tmpl-header-title">Value</div>
          <div className="tmpl-header-title"></div>
          <div className="tmpl-header-title"></div>
        </div>
        {props.filterRows?.map((filterRow: FilterExpressionViewModel) => (
          <Filter
            key={filterRow.id}
            cache={props.cache}
            uiElementGroupId={props.uiElementGroupId}
            filterRow={filterRow}
            appliedfilterCount={props.filterRows.length}
            onFilterTargetChange={(value, id) => {
              setValidationErrors((prev) => {
                const next = new Set(prev);
                next.delete(id);
                return next;
              });
              props.onFilterTargetChange(value, id);
            }}
            onOperatorChange={(value, id) => {
              setValidationErrors((prev) => {
                const next = new Set(prev);
                next.delete(id);
                return next;
              });
              props.onOperatorChange(value, id);
            }}
            onFilterValueChange={(value, id) => {
              setValidationErrors((prev) => {
                const next = new Set(prev);
                next.delete(id);
                return next;
              });
              props.onFilterValueChange(value, id);
            }}
            onCriteriaToggle={props.onCriteriaToggle}
            onAddFilter={props.onAddFilter}
            onDeleteFilter={props.onDeleteFilter}
            loadSupportiveData={props.loadSupportiveData}
            hasError={validationErrors.has(filterRow.id)}
          />
        ))}
      </div>
      <div className="tmpl-action-container">
        <FactoryRenderer
          title="Clear Filter"
          onClick={props.onClear}
          uiElementType="WIDGET"
          widgetType="BUTTON"
          widgetStyle={{ className: "qo-btn qo-btn-outline-danger qo-btn-md tmpl-button" }}
          disabled={props.isClearDisabled}
        />
        <div className="tmpl-criteria-input-container" title={props.criteria}>
          <p
            id={`tmpl-criteria-input-${props.uiElementGroupId ?? ""}`}
            className="tmpl-criteria-input"
            contentEditable={true}
          >
            {props.criteria}
          </p>
          <FactoryRenderer
            name="right"
            widgetStyle={{ className: "tmpl-criteria-input-icon" }}
            onClick={props.onCriteriaApplied}
            uiElementType="WIDGET"
            widgetType="ICON"
          />
          <FactoryRenderer
            onClick={props.onCopyToClipboard}
            widgetStyle={{ className: "tmpl-criteria-input-icon" }}
            name="copy"
            uiElementType="WIDGET"
            widgetType="ICON"
          />
        </div>
        <div>
          <span className="tmpl-cancel-action" onClick={props.onCancel}>
            Cancel
          </span>
          <FactoryRenderer
            widgetStyle={{ className: "qo-btn qo-btn-primary qo-btn-md tmpl-button" }}
            onClick={validateAndApply}
            uiElementType="WIDGET"
            widgetType="BUTTON"
            title="Apply Filter"
            themeColor="primary"
            disabled={props.isApplyDisabled}
          />
        </div>
      </div>
    </>
  );
};

export default FilterPopupView;
