import React, {
  useRef,
  useState,
  useEffect,
  useCallback,
  Fragment,
} from "react";
import SearchIcon from "@mui/icons-material/Search";
import { Input } from "../Input";
import { Select } from "../Select";
import CloseIcon from "@mui/icons-material/Close";
import TuneIcon from "@mui/icons-material/Tune";
import { debounce } from "../../utils/debounce";
import TableSortIcon from "../../assets/tableSortIcon.svg";
import TableSortAscIcon from "../../assets/Up.svg";
import TableSortDescIcon from "../../assets/Down.svg";
import { Badge } from "@mui/material";
import { Tooltip } from "../Tooltip";
import { DatePicker } from "../DatePicker";
import { DateRangePicker } from "../DateRangePicker";
import moment from "moment";
import {
  parseInlineSearchValue,
  buildFilterModelEntry,
  syncFiltersWithModal,
} from "../Table/filterUtils";
function AgGridHeader({
  children,
  sortModel,
  handleInlineSearch,
  handleClearSearchInline,
  handleCloseInputField,
  debounceTime,
  initialFilters,
  enableHeaderTextWrap = true,
  ...rest
}) {
  // Guard against undefined rest.column or rest.api
  if (!rest?.column || !rest?.api) {
    return null;
  }

  // Helper function to get label from dropdown options for boolean dropdowns
  const getLabelFromDropdownValue = (value, columnDef) => {
    if (
      !columnDef?.isThirdOptionDropdownIsBoolean ||
      !columnDef?.thirdOptionDropdownOptions ||
      !Array.isArray(columnDef.thirdOptionDropdownOptions)
    ) {
      return value;
    }

    // Find the option that matches the value
    const option = columnDef.thirdOptionDropdownOptions.find((opt) => {
      // Handle both object { label, value } and string formats
      const optValue = typeof opt === "object" ? opt.value : opt;
      const filterValue = String(value || "").toLowerCase();
      const optValueStr = String(optValue || "").toLowerCase();

      // Match exact value or common variations
      return (
        optValueStr === filterValue ||
        optValueStr === filterValue.replace(/\s+/g, "")
      );
    });

    // Return the label if found, otherwise return the original value
    if (option) {
      return typeof option === "object" ? option.label : option;
    }

    return value;
  };

  // Helper function to get option object from value
  // When reading from filter model, convert value like "true" back to option object { label: "Active", value: "true" }
  const getOptionFromDropdownValue = (value, columnDef) => {
    // Check if column has dropdown options
    if (
      !columnDef?.thirdOptionDropdownOptions ||
      !Array.isArray(columnDef.thirdOptionDropdownOptions) ||
      !value
    ) {
      return value;
    }

    const valueStr = String(value || "")
      .toLowerCase()
      .trim();
    if (!valueStr) {
      return value;
    }

    // Find the option that matches the value
    const option = columnDef.thirdOptionDropdownOptions.find((opt) => {
      const optValue = typeof opt === "object" ? opt.value : opt;
      const optValueStr = String(optValue || "")
        .toLowerCase()
        .trim();
      return optValueStr === valueStr;
    });

    // Return the full option object if found, otherwise return the original value
    if (option) {
      return typeof option === "object"
        ? option
        : { label: option, value: option };
    }

    return value;
  };

  // Helper function to get value from dropdown label (reverse lookup)
  // When user types a label like "Active", convert it to the corresponding value like "true"
  const getValueFromDropdownLabel = (inputText, columnDef) => {
    // Check if column has dropdown options
    if (!columnDef?.thirdOptionDropdownOptions || !inputText) {
      return inputText;
    }

    const inputTextLower = String(inputText || "")
      .toLowerCase()
      .trim();
    if (!inputTextLower) {
      return inputText;
    }

    // First, try exact match (case-insensitive)
    let option = columnDef.thirdOptionDropdownOptions.find((opt) => {
      const optLabel = typeof opt === "object" ? opt.label : opt;
      const optLabelStr = String(optLabel || "")
        .toLowerCase()
        .trim();
      return optLabelStr === inputTextLower;
    });

    // If no exact match, try partial match (for typing)
    if (!option) {
      option = columnDef.thirdOptionDropdownOptions.find((opt) => {
        const optLabel = typeof opt === "object" ? opt.label : opt;
        const optLabelStr = String(optLabel || "")
          .toLowerCase()
          .trim();
        // Match if label starts with input or input starts with label
        return (
          optLabelStr.startsWith(inputTextLower) ||
          inputTextLower.startsWith(optLabelStr)
        );
      });
    }

    // Return the value if found, otherwise return the original input text
    if (option) {
      return typeof option === "object" ? option.value : option;
    }

    return inputText;
  };
  const menuRef = useRef();
  const inputRef = useRef();
  const textRef = useRef();
  const [showInputField, setShowInputField] = useState(false);
  const [isTextTruncated, setIsTextTruncated] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [menuVisible, setMenuvisible] = useState(false);
  const [columnWidth, setColumnWidth] = useState({});
  const [currentSort, setCurrentSort] = useState(
    rest?.column?.getSort?.() ?? null
  );
  const [hasActiveSearch, setHasActiveSearch] = useState(false);
  const [selectedDate, setSelectedDate] = useState(null);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [isInputFocused, setIsInputFocused] = useState(false);
  const originalSuppressHeaderKeyboardEventRef = useRef(
    rest?.column?.colDef?.suppressHeaderKeyboardEvent
  );
  const filterModel = rest.api.getFilterModel();
  const isFilterAppliedChanged = filterModel[rest.column?.colId];
  const [isOverflowText, setIsOverflowText] = useState(false);
  const headerTextRef = useRef(null);
  const containerRef = useRef(null);
  const [containerHeight, setContainerHeight] = useState(0);
  const onFilterChanged = useCallback(() => {
    const newFilterModel = rest?.api?.getFilterModel();

    const columnId = rest?.column?.field || rest?.column?.colId;
    const columnFilter = newFilterModel?.[columnId];
    let filterValue = "";

    if (columnFilter) {
      if (rest?.column?.colDef?.filter === "agDateColumnFilter") {
        const dateFrom = columnFilter?.dateFrom;
        const dateTo = columnFilter?.dateTo;

        // Handle date range
        if (dateFrom && dateTo) {
          setStartDate(moment(dateFrom));
          setEndDate(moment(dateTo));
          // Handle both Date objects and strings
          const dateFromStr =
            dateFrom instanceof Date
              ? moment(dateFrom).format("YYYY-MM-DD")
              : typeof dateFrom === "string"
              ? dateFrom.split(" ")[0]
              : dateFrom;
          const dateToStr =
            dateTo instanceof Date
              ? moment(dateTo).format("YYYY-MM-DD")
              : typeof dateTo === "string"
              ? dateTo.split(" ")[0]
              : dateTo;
          filterValue = `${dateFromStr} - ${dateToStr}`;
        }
        // Handle single date
        else if (dateFrom) {
          filterValue = moment(dateFrom);
          setSelectedDate(filterValue);
          // Handle both Date objects and strings
          if (dateFrom instanceof Date) {
            filterValue = moment(dateFrom).format("YYYY-MM-DD");
          } else if (typeof dateFrom === "string") {
            filterValue = dateFrom.split(" ")[0];
          } else {
            filterValue = dateFrom;
          }
        }
      } else {
        filterValue = columnFilter?.filter;

        // If thirdOptionAsDropdown is true, set the selected dropdown option
        if (rest?.column?.colDef?.thirdOptionAsDropdown && filterValue) {
          const dropdownOptions =
            rest?.column?.colDef?.thirdOptionDropdownOptions;
          const option = Array.isArray(dropdownOptions)
            ? dropdownOptions.find((opt) => {
                const optValue = typeof opt === "object" ? opt.value : opt;
                return String(optValue) === String(filterValue);
              })
            : null;
          if (option) {
            setSelectedDropdownOption(
              typeof option === "object"
                ? option
                : { label: option, value: option }
            );
          }
        } else {
          // For boolean dropdowns, show the label instead of the raw value
          const displayValue = getLabelFromDropdownValue(
            filterValue,
            rest?.column?.colDef
          );
          setSearchText(displayValue);
        }
      }
      // Check for advanced filter model
      const gridModel = rest?.api?.getModel?.();
      const advancedFilterModel = gridModel?.advancedFilterModel;
      if (
        advancedFilterModel &&
        rest?.column?.colId &&
        advancedFilterModel[rest.column.colId]
      ) {
        // Advanced filter exists for this column
      }
    }

    // ✅ Reset if filter removed
    if (!filterValue) {
      setSearchText("");
      setSelectedDropdownOption(null);
      setSelectedDate(null);
      setStartDate(null);
      setEndDate(null);
      setHasActiveSearch(false);
    } else {
      // If thirdOptionAsDropdown is true, the dropdown option is already set above
      if (!rest?.column?.colDef?.thirdOptionAsDropdown) {
        // For boolean dropdowns, show the label instead of the raw value
        const displayValue = getLabelFromDropdownValue(
          filterValue,
          rest?.column?.colDef
        );
        setSearchText(displayValue);
      }
      setHasActiveSearch(true);
    }
  }, [
    rest?.api,
    rest?.column?.colId,
    rest?.column?.field,
    rest?.column?.colDef?.thirdOptionDropdownOptions,
  ]);

  // Initialize dropdown options when thirdOptionAsDropdown is true
  useEffect(() => {
    if (rest?.column?.colDef?.thirdOptionAsDropdown) {
      const options = rest?.column?.colDef?.thirdOptionDropdownOptions || [];
      setCurrentDropdownOptions(options);
    }
  }, [
    rest?.column?.colDef?.thirdOptionAsDropdown,
    rest?.column?.colDef?.thirdOptionDropdownOptions,
  ]);

  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  // State for dropdown selection when thirdOptionAsDropdown is true
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [selectedDropdownOption, setSelectedDropdownOption] = useState(null);
  const [currentDropdownOptions, setCurrentDropdownOptions] = useState([]);

  useEffect(() => {
    // Load initial filter state when grid loads
    const filterModel = rest.api.getFilterModel();
    if (filterModel[rest.column?.colId]) {
      const columnFilter =
        filterModel[rest?.column?.field || rest?.column?.colId];
      let filterValue;
      // Handle different filter types
      if (rest?.column?.colDef?.filter === "agDateColumnFilter") {
        const dateFrom = columnFilter?.dateFrom;
        const dateTo = columnFilter?.dateTo;

        // Handle date range
        if (dateFrom && dateTo) {
          setStartDate(moment(dateFrom));
          setEndDate(moment(dateTo));
          filterValue = `${dateFrom} - ${dateTo}`;
        }
        // Handle single date
        else if (dateFrom) {
          filterValue = moment(dateFrom);
          setSelectedDate(filterValue);
        }
      } else {
        // For other columns, use filter
        filterValue = columnFilter?.filter;

        // If thirdOptionAsDropdown is true, set the selected dropdown option
        if (rest?.column?.colDef?.thirdOptionAsDropdown && filterValue) {
          const options =
            rest?.column?.colDef?.thirdOptionDropdownOptions || [];
          const option = options.find((opt) => {
            const optValue = typeof opt === "object" ? opt.value : opt;
            return String(optValue) === String(filterValue);
          });
          if (option) {
            setSelectedDropdownOption(
              typeof option === "object"
                ? option
                : { label: option, value: option }
            );
          }
        } else {
          // For boolean dropdowns, show the label instead of the raw value
          const displayValue = getLabelFromDropdownValue(
            filterValue,
            rest?.column?.colDef
          );
          setSearchText(displayValue);
        }
      }
      setHasActiveSearch(!!filterValue);
    } else {
      setSearchText("");
      setSelectedDropdownOption(null);
      setSelectedDate(null);
      setStartDate(null);
      setEndDate(null);
      setHasActiveSearch(false);
    }
    rest.api.addEventListener("filterChanged", onFilterChanged);
    return () => {
      rest.api.removeEventListener("filterChanged", onFilterChanged);
    };
  }, [isFilterAppliedChanged, onFilterChanged, currentDropdownOptions]);

  const handleSearchChange = (value) => {
    // Handle custom inline search callback
    if (handleInlineSearch) {
      handleInlineSearch?.(value);
      rest?.onFilterChanged?.(rest);
      return;
    }

    setTimeout(() => {
      try {
        // Step 1: Parse the search value based on column type
        const { inputValue, filterType } = parseSearchValue(value);

        // Step 2: Apply filter to AG Grid
        applyFilterToGrid(inputValue, filterType);

        // Step 3: Sync with advance search modal
        syncFiltersWithModal(
          rest.api,
          rest.column.colId,
          inputValue,
          rest?.column?.colDef,
          rest?.colDefs,
          rest?.setValue,
          rest?.setInitialFilters,
          getOptionFromDropdownValue
        );

        // Step 4: Trigger filter change callbacks
        rest?.api?.onFilterChanged?.();
        rest?.onFilterChanged?.(rest);
      } catch (error) {
        console.warn("Error during filter operation:", error);
      }
    }, 0);
  };

  // Helper: Parse search value (handles dropdowns and regular columns)
  const parseSearchValue = (value) => {
    if (rest?.column?.colDef?.thirdOptionAsDropdown) {
      // Dropdown column: value is already the option value
      // Use "equals" for boolean columns, "contains" for others
      const isBoolean = rest?.column?.colDef?.dataType === "boolean";
      return {
        inputValue: value,
        filterType: isBoolean ? "equals" : "contains",
      };
    } else {
      // Regular column: use utility function
      const parsed = parseInlineSearchValue(
        value,
        rest?.column?.colDef,
        rest.api,
        rest.column.colId
      );
      return {
        inputValue: parsed.parsedValue,
        filterType: parsed.filterType,
      };
    }
  };

  // Helper: Apply filter to AG Grid
  const applyFilterToGrid = (inputValue, filterType) => {
    const currentFilterModel = rest?.sortModel || rest.api.getFilterModel();
    const filterEntry = buildFilterModelEntry(
      inputValue,
      filterType,
      rest?.column?.colDef
    );

    // If filterEntry is undefined (invalid/empty value), remove the filter
    if (filterEntry === undefined) {
      delete currentFilterModel[rest.column.colId];
    } else {
      currentFilterModel[rest.column.colId] = filterEntry;
    }

    rest.api.setFilterModel(currentFilterModel);
    // Handle empty state overlay after filters are applied
    setTimeout(() => {
      if (rest?.api) {
        const displayedRowCount = rest.api.getDisplayedRowCount();
        if (displayedRowCount === 0) {
          rest.api.showNoRowsOverlay();
        } else {
          rest.api.hideOverlay();
        }
      }
    }, 100);
  };

  const debouncedHandleSearchChange = useCallback(
    debounce((value) => {
      handleSearchChange(value);
    }, debounceTime),
    []
  );

  const handleSearch = (e) => {
    e.stopPropagation();
    if (rest?.column?.colDef?.filter === "agDateColumnFilter") {
      setShowDatePicker((prev) => !prev);
    } else if (rest?.column?.colDef?.thirdOptionAsDropdown) {
      // For dropdown columns, show the input field which will render the dropdown
      setShowInputField((prev) => !prev);
      // Open the dropdown when the search icon is clicked
      if (!showInputField) {
        setTimeout(() => {
          setIsDropdownOpen(true);
        }, 0);
      }
    } else {
      setShowInputField((prev) => !prev);
    }
    setColumnWidth((prev) => ({
      ...prev,
      [rest?.column?.colId]: rest?.column?.actualWidth,
    }));
  };
  const onCloseIconClick = (colId) => {
    setSearchText("");
    setSelectedDropdownOption(null);
    setSelectedDate(null);
    setStartDate(null);
    setEndDate(null);
    setHasActiveSearch(false);
    rest.api.destroyFilter(colId);

    // Remove from modal filters too
    const currentFilters = rest?.getValues?.()?.filters || [];
    const updatedFilters = currentFilters.filter(
      (f) => f?.column?.value !== colId
    );
    rest?.setValue?.("filters", updatedFilters);
    rest?.setInitialFilters?.(updatedFilters);

    if (rest.onFilterChanged) {
      rest.onFilterChanged(rest);
    }
  };

  const handleClickOutside = (event) => {
    setMenuvisible(false);
  };

  useEffect(() => {
    document.addEventListener("click", handleClickOutside);

    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [menuVisible]);

  const onHeaderClick = () => {
    if (rest.applySort) {
      rest.applySort(rest.column.colId);
      return;
    }
    if (rest?.column?.colDef?.sortable) {
      const currentSortModel = rest.api.getColumnState();
      const currentSort = currentSortModel.find(
        (model) => model.colId === rest.column.colId
      );
      const newSort =
        currentSort?.sort === null
          ? "asc"
          : currentSort?.sort === "asc"
          ? "desc"
          : null;
      rest.api.applyColumnState({
        state: [{ colId: rest.column.colId, sort: newSort }],
        defaultState: { sort: null },
      });
    }
  };

  useEffect(() => {
    const onSortChanged = () =>
      setCurrentSort(rest?.column?.getSort?.() ?? null);
    rest?.api?.addEventListener("sortChanged", onSortChanged);
    return () => rest?.api?.removeEventListener("sortChanged", onSortChanged);
  }, [rest.api, rest.column]);

  const onColumnMoved = (params) => {
    if (params?.column?.colId && (showInputField || showDatePicker)) {
      setColumnWidth((prev) => ({
        ...prev,
        [params.column.colId]: params.column.actualWidth,
      }));
      // Store width in column state for cell renderers to access
      rest.api.applyColumnState({
        state: [
          {
            colId: params.column.colId,
            width: params.column.actualWidth,
          },
        ],
        defaultState: { width: null },
      });
    }
  };

  useEffect(() => {
    if (rest) {
      rest?.api?.addEventListener("columnResized", onColumnMoved);
    }
    return () => {
      rest?.api?.removeEventListener("columnResized", onColumnMoved);
    };
  }, [rest]);

  useEffect(() => {
    const colDef = rest?.column?.colDef;
    if (!colDef) return;

    if (isInputFocused) {
      if (originalSuppressHeaderKeyboardEventRef.current === undefined) {
        originalSuppressHeaderKeyboardEventRef.current =
          colDef.suppressHeaderKeyboardEvent;
      }
      colDef.suppressHeaderKeyboardEvent = () => true;
    } else {
      colDef.suppressHeaderKeyboardEvent =
        originalSuppressHeaderKeyboardEventRef.current;
    }

    return () => {
      if (colDef) {
        colDef.suppressHeaderKeyboardEvent =
          originalSuppressHeaderKeyboardEventRef.current;
      }
    };
  }, [isInputFocused, rest?.column?.colId]);

  useEffect(() => {
    if (containerRef.current) {
      setContainerHeight(containerRef.current?.clientHeight);
    }
  }, []);

  return (
    <div
      className={`custom-ag-header-container ${
        rest?.column?.colDef?.checkboxSelection ? "checkbox-selection" : ""
      } ${(rest?.column?.colDef?.customHeaderIcons || !rest?.column?.colDef?.suppressMenu || rest?.column?.colDef?.isSearchable) ? "with-icons" : ""}`}
      onClick={() => rest.onClick()}
      ref={containerRef}
    >
      {showDatePicker ? (
        <div
          className={`ia-search-input-field ${
            (columnWidth[rest?.column?.colId] ?? rest?.column?.actualWidth) <
            200
              ? "ia-search-input-narrow"
              : ""
          }`}
        >
          {rest?.column?.colDef?.thirdOptionAsDateRangePicker ? (
            <DateRangePicker
              startDate={startDate}
              endDate={endDate}
              setStartDate={setStartDate}
              setEndDate={setEndDate}
              handleDatesChange={(start, end) => {
                setStartDate(start);
                setEndDate(end);
              }}
              withPortal
              fullWidth
              isAgGridCellRenderer
              displayFormat={
                rest?.column?.colDef?.displayFormat || "MM-DD-YYYY"
              }
              minDate={new Date("2000-01-01")}
              maxDate={new Date("2100-12-31")}
              onResetClick={() => {
                setStartDate(null);
                setEndDate(null);
                handleSearchChange(null);
                setShowDatePicker(false);
              }}
              onPrimaryButtonClick={() => {
                if (startDate && endDate) {
                  handleSearchChange({ startDate, endDate });
                }
                setShowDatePicker(false);
              }}
              onSecondaryButtonClick={() => {
                setShowDatePicker(false);
              }}
              customIcon={
                rest?.column?.colDef?.advanceSearchEnabled && (
                  <TuneIcon
                    className="ia-search-input-field-custom-icon"
                    onClick={(e) => {
                      e.stopPropagation();
                      if (rest.onAdvanceSearchClick) {
                        rest.onAdvanceSearchClick(rest.column);
                        return;
                      }
                      rest.toggleAdvanceSearch(
                        rest?.column?.colDef
                          ?.toShowDuplicateColumnInAdvanceSearch
                          ? rest?.column?.colDef?.columnFieldsInAdvanceSearch
                            ? rest?.column?.colDef?.columnFieldsInAdvanceSearch
                            : rest.column.colId
                          : rest.column.colId
                      );
                    }}
                  />
                )
              }
            />
          ) : (
            <DatePicker
              selectedDate={selectedDate}
              setSelectedDate={setSelectedDate}
              placeholder="Select Date"
              withPortal
              fullWidth
              isAgGridCellRenderer
              displayFormat={
                rest?.column?.colDef?.displayFormat || "MM-DD-YYYY"
              }
              showMonthYearSelect
              minDate={new Date("2000-01-01")}
              maxDate={new Date("2100-12-31")}
              onTertiaryButtonClick={() => {
                setSelectedDate(null);
                handleSearchChange(null);
                setShowDatePicker(false);
              }}
              onPrimaryButtonClick={() => {
                handleSearchChange(selectedDate);
                setShowDatePicker(false);
              }}
              onSecondaryButtonClick={() => {
                setShowDatePicker(false);
              }}
              customIcon={
                rest?.column?.colDef?.advanceSearchEnabled && (
                  <TuneIcon
                    className="ia-search-input-field-custom-icon"
                    onClick={() => {
                      if (rest.onAdvanceSearchClick) {
                        rest.onAdvanceSearchClick(rest.column);
                        return;
                      }
                      rest.toggleAdvanceSearch(
                        rest?.column?.colDef
                          ?.toShowDuplicateColumnInAdvanceSearch
                          ? rest?.column?.colDef?.columnFieldsInAdvanceSearch
                            ? rest?.column?.colDef?.columnFieldsInAdvanceSearch
                            : rest.column.colId
                          : rest.column.colId
                      );
                    }}
                  />
                )
              }
            />
          )}
          <CloseIcon
            className="ia-search-input-field-close-icon"
            onClick={() => {
              handleCloseInputField?.();
              setShowDatePicker(false);
            }}
            style={{ cursor: "pointer" }}
          />
        </div>
      ) : showInputField ? (
        <div
          className={`ia-search-input-field ${
            (columnWidth[rest?.column?.colId] ?? rest?.column?.actualWidth) <
            200
              ? "ia-search-input-narrow"
              : ""
          }`}
        >
          {rest?.column?.colDef?.thirdOptionAsDropdown &&
          !rest?.column?.colDef?.toShowDuplicateColumnInAdvanceSearch ? (
            <div
              id="ia-select-option-dropdown-container"
              style={{
                position: "relative",
                width: selectedDropdownOption ? "66%" : "100%",
              }}
            >
              <Select
                placeholder="Select option"
                initialOptions={currentDropdownOptions}
                isOpen={isDropdownOpen}
                setIsOpen={setIsDropdownOpen}
                currentOptions={currentDropdownOptions}
                setCurrentOptions={setCurrentDropdownOptions}
                selectedOptions={selectedDropdownOption || null}
                setSelectedOptions={(option) => {
                  setSelectedDropdownOption(option);
                  if (option) {
                    const value =
                      typeof option === "object" ? option.value : option;
                    setHasActiveSearch(true);
                    handleSearchChange(value);
                  } else {
                    setHasActiveSearch(false);
                    handleSearchChange(null);
                  }
                }}
                isClearable={true}
                onClearAll={() => {
                  setSelectedDropdownOption(null);
                  setHasActiveSearch(false);
                  handleSearchChange(null);
                }}
                withPortal
                // minWidth="136px"
                minWidth="100%"
              />
              {rest?.column?.colDef?.advanceSearchEnabled && (
                <TuneIcon
                  className="ia-search-input-field-custom-icon"
                  id="toggle-advance-search-icon"
                  style={{
                    position: "absolute",
                    right: selectedDropdownOption ? "44px" : "28px",
                    top: "50%",
                    transform: "translateY(-50%)",
                    cursor: "pointer",
                    zIndex: 1,
                    pointerEvents: "auto",
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    if (rest.onAdvanceSearchClick) {
                      rest.onAdvanceSearchClick(rest.column);
                      return;
                    }
                    rest?.toggleAdvanceSearch(
                      rest?.column?.colDef?.toShowDuplicateColumnInAdvanceSearch
                        ? rest?.column?.colDef?.columnFieldsInAdvanceSearch
                          ? rest?.column?.colDef?.columnFieldsInAdvanceSearch
                          : rest.column.colId
                        : rest.column.colId
                    );
                  }}
                />
              )}
            </div>
          ) : (
            <Input
              ref={inputRef}
              rightIcon={
                <Fragment>
                  {searchText?.toString()?.length > 0 &&
                    (columnWidth[rest?.column?.colId] ??
                      rest?.column?.actualWidth) >= 200 && (
                      <CloseIcon
                        onClick={() => {
                          if (handleClearSearchInline) {
                            handleClearSearchInline(rest);
                          }
                          onCloseIconClick(rest.column.colId);
                        }}
                      />
                    )}
                  {rest?.column?.colDef?.advanceSearchEnabled && (
                    <TuneIcon
                      onClick={() => {
                        if (rest.onAdvanceSearchClick) {
                          rest.onAdvanceSearchClick(rest.column);
                          return;
                        }
                        rest.toggleAdvanceSearch(
                          rest?.column?.colDef
                            ?.toShowDuplicateColumnInAdvanceSearch
                            ? rest?.column?.colDef?.columnFieldsInAdvanceSearch
                              ? rest?.column?.colDef
                                  ?.columnFieldsInAdvanceSearch
                              : rest.column.colId
                            : rest.column.colId,
                          searchText
                        );
                      }}
                    />
                  )}
                </Fragment>
              }
              value={searchText}
              placeholder="Search"
              onChange={(e) => {
                setSearchText(e.target.value);
                setHasActiveSearch(!!e.target.value);
                debouncedHandleSearchChange(e.target.value);
              }}
              isDisabled={
                rest?.column?.colDef?.toShowDuplicateColumnInAdvanceSearch
              }
              iconClickOnDisabled={
                rest?.column?.colDef?.toShowDuplicateColumnInAdvanceSearch
              }
            />
          )}
          <CloseIcon
            className="ia-search-input-field-close-icon"
            onClick={() => {
              handleCloseInputField?.();
              setShowInputField(false);
              setSelectedDropdownOption(null);
            }}
            style={{ cursor: "pointer" }}
          />
        </div>
      ) : (
        // Original simple structure when enableHeaderTextWrap is false
        <React.Fragment>
          <div
            className={`ag-header-cell-text ${
              rest?.column?.colDef?.sortable ? "sortable" : ""
            } ${enableHeaderTextWrap ? "header-wrap-enabled" : ""}`}
          >
            {rest?.column?.colDef?.field === "Selection" ||
            rest?.column?.colDef?.checkboxSelection ? (
              children
            ) : (
              <div
                className="header-text-content"
                ref={headerTextRef}
                onMouseEnter={() => {
                  setIsOverflowText(
                    headerTextRef.current?.scrollWidth >
                      headerTextRef.current?.clientWidth ||
                      headerTextRef?.current?.scrollHeight >
                        headerTextRef?.current?.clientHeight + 1
                  );
                }}
                style={{ WebkitLineClamp: containerHeight > 40 ? 4 : 2 }}
              >
                <Tooltip
                  variant="tertiary"
                  title={
                    isOverflowText && children !== "Selection" ? children : ""
                  }
                  orientation="top"
                >
                  {children}
                </Tooltip>
              </div>
            )}
            {rest?.column?.colDef?.sortable && (
              <img
                src={
                  currentSort === "asc"
                    ? TableSortAscIcon
                    : currentSort === "desc"
                    ? TableSortDescIcon
                    : TableSortIcon
                }
                alt="TableSortIcon"
                className="ia-table-sort-icon"
                onClick={onHeaderClick}
              />
            )}
          </div>
          <div
            className={`ia-icon-div ${
              hasActiveSearch ? "has-active-search" : ""
            } ${menuVisible ? "menu-visible" : ""}`}
          >
            {rest?.column?.colDef?.customHeaderIcons &&
              rest?.column?.colDef?.customHeaderIcons.map((icon) => {
                return icon;
              })}
            {rest?.column?.colDef?.isSearchable &&
              (hasActiveSearch || !showInputField) && (
                <Badge variant="dot" invisible={!hasActiveSearch}>
                  <SearchIcon
                    fontSize="small"
                    onClick={
                      rest.onColumnSearchClick
                        ? () => {
                            rest.onColumnSearchClick(rest);
                            setShowInputField(true);
                            if (
                              rest?.column?.colDef?.filter ===
                              "agDateColumnFilter"
                            ) {
                              setShowDatePicker(true);
                            } else if (
                              rest?.column?.colDef?.thirdOptionAsDropdown
                            ) {
                              // Open the dropdown when the search icon is clicked
                              setTimeout(() => {
                                setIsDropdownOpen(true);
                              }, 0);
                            }
                          }
                        : handleSearch
                    }
                    style={{
                      color: "#60697D",
                      cursor: "pointer",
                      backgroundColor: hasActiveSearch && "#ECEEFD",
                      display:
                        menuVisible && !hasActiveSearch ? "none" : "block",
                    }}
                  />
                </Badge>
              )}
            {!rest?.column?.colDef?.suppressMenu && (
              <div className="custom-ag-header-icons">
                <button
                  ref={menuRef}
                  className={`custom-ag-menu-icon-button`}
                  onClick={(e) => {
                    e.stopPropagation();
                    rest.showColumnMenu(menuRef.current);
                    setMenuvisible(true);
                  }}
                />
              </div>
            )}
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

export default AgGridHeader;
