import { useState } from "react";
import CustomTextFieldRange from "./fieldsType/CustomTextFieldRange";
import CustomSelect from "./fieldsType/CustomSelect";
import CustomDatePicker from "../CustomDatePicker";
import CustomDatePickerRange from "./fieldsType/CustomDate/CustomDatePickerRange";
import CustomSelectMultiple from "./fieldsType/CustomSelectMultiple";
import CustomTextField from "./fieldsType/CustomTextField";
import FilterOptionList from "./FilterOptionList";

const filterModeOptionFa = {
  equals: "برابر",
  notEquals: "نابرابر",
  contains: "شامل",
  lessThan: "کوچکتر",
  greaterThan: "بزرگتر",
  fuzzy: "فازی",
  between: "مابین",
};

function FilterField({
  item,
  filterParameters,
  handleChange,
  handleBlur,
  dependencyFieldValue,
  setFieldValue,
  resetForm,
  errors,
}) {
  const [anchorEl, setAnchorEl] = useState(null);
  const defaultFilterTranslation =
    filterModeOptionFa[filterParameters.filterMode] ||
    filterParameters.filterMode;

  const handleOpenFilterBox = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const renderField = () => {
    const commonProps = {
      item,
      filterParameters,
      defaultFilterTranslation,
      handleOpenFilterBox,
      dependencyFieldValue,
      setFieldValue,
      handleChange,
      handleBlur,
      errors,
    };

    switch (filterParameters.datatype) {
      case "numeric":
        if (filterParameters.filterMode === "between") {
          return <CustomTextFieldRange {...commonProps} />;
        }
        if (filterParameters.filterMode === "equals") {
          return item.SelectComponent ? (
            <item.SelectComponent {...commonProps} />
          ) : (
            <CustomSelect {...commonProps} />
          );
        }
        break;
      case "date":
        if (filterParameters.filterMode === "equals") {
          return <CustomDatePicker {...commonProps} />;
        }
        if (filterParameters.filterMode === "between") {
          return <CustomDatePickerRange {...commonProps} />;
        }
        break;

      case "array":
        if (filterParameters.filterMode === "equals") {
          return <CustomSelectMultiple {...commonProps} />;
        }
        break;

      default:
        return <CustomTextField {...commonProps} />;
    }
  };

  return (
    <>
      {renderField()}
      {Array.isArray(item.filterModeOptions) && (
        <FilterOptionList
          item={item}
          anchorEl={anchorEl}
          setAnchorEl={setAnchorEl}
          filterParameters={filterParameters}
          filterType={filterParameters.filterMode}
          handleChange={handleChange}
          resetForm={resetForm}
          filterOption={item.filterModeOptions}
          filterModeOptionFa={filterModeOptionFa}
        />
      )}
    </>
  );
}

export default FilterField;
