import React, {
  forwardRef,
  useEffect,
  useState,
  useRef,
  useCallback,
  useMemo,
} from "react";
import { Checkbox } from "../Checkbox/index";
import { Input } from "../Input";
import { IconButton } from "@mui/material";
import { DragIndicator } from "@mui/icons-material";
import SearchIcon from "@mui/icons-material/Search";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";
import saveViewIcon from "../../assets/saveViewIcon.svg";
import { Button } from "../Button";
import { Modal } from "../Modal";
import { RadioButtonGroup } from "../RadioButtonGroup";
import { Select } from "../Select";
import { Badge } from "../Badge";
import { Prompt } from "../Prompt";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import { isViewNameUnique } from "../../utils/helper";
import saveViewEditIcon from "../../assets/saveViewEditIcon.svg";
import saveViewDeleteIcon from "../../assets/saveViewDeleteIcon.svg";
import defaultViewIcon from "../../assets/defaultViewIcon.svg";
import defaultViewActiveIcon from "../../assets/defaultViewIconActive.svg";
import {
  DndContext,
  closestCenter,
  useSensor,
  useSensors,
  MouseSensor,
  TouchSensor,
} from "@dnd-kit/core";
import { SortableContext, useSortable, arrayMove } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { debounce } from "../../utils/debounce";

export const onColMenuFreezeClick = (params) => {
  const { pinned } = params.column;
  // if column is pinned then unpin, vice-versa
  if (pinned) {
    freezeColumn(params, false);
  } else {
    freezeColumn(params, true);
  }
};

export const freezeColumn = (params, isPinned) => {
  const { colId } = params.column;
  params.columnApi.applyColumnState({
    state: [{ colId, pinned: isPinned ? "left" : null }],
  });
};

export const onColMenuAutoAdjustClick = (params) => {
  let colDefExtra = { ...params.column.colDef.extra };
  // delete colDefExtra.width;
  params.column.colDef.extra = colDefExtra;
  params.columnApi.autoSizeColumn(params.column);
};

export const sortFunc = (columnData, sortBy, api) => {
  // applyColumnState - to manually set the sort order for a particular column
  api.columnApi.applyColumnState({
    state: [{ colId: columnData.colId, sort: sortBy }],
    defaultState: { sort: null },
  });
};

export const getMainMenuItems = (params) => {
  const { onFontSizeChange, onNumberFormatChange } = params;
  const { colDef, pinned, sort, actualWidth } = params.column;
  const columnMenuItems = [];

  // grid column menu title
  columnMenuItems.push(
    {
      name: "Column Settings",
      cssClasses: ["settings-main-container"],
    },
    "separator"
  );

  // ability to sort column
  columnMenuItems.push({
    name: "Sort",
    subMenu: [
      {
        name: "Sort A to Z",
        action: () => sortFunc(params.column, "asc", params),
        checked: sort === "asc",
      },
      {
        name: "Sort Z to A",
        checked: sort === "desc",
        action: () => sortFunc(params.column, "desc", params),
      },
      {
        name: "Reset",
        action: () => sortFunc(params.column, null, params),
      },
    ],
    disabled: false,
  });

  // ability to pin/unpin columns based on current state
  columnMenuItems.push({
    name: pinned ? "Unfreeze Column" : "Freeze Column",
    action: () => {
      onColMenuFreezeClick(params);
    },
  });

  // ability to adjust column width to custom or auto
  columnMenuItems.push({
    name: "Column width",
    subMenu: [
      {
        name: "Auto Adjust",
        action: () => {
          onColMenuAutoAdjustClick(params);
        },
        // if extra.width property is not present- column is auto adjusted
        checked: actualWidth !== colDef?.extra?.width,
      },
      {
        name: "Custom width",
        action: () => {
          // add extra.width property for custom width
          params.columnApi.setColumnWidth(
            params.column.colDef,
            colDef?.extra?.width
          );
        },
        // if extra.width property is present- column has custom width
        checked: colDef?.extra?.width === actualWidth,
        disabled: !colDef?.extra?.width,
      },
    ],
  });

  // text wrap action
  columnMenuItems.push({
    name: "Wrap Text",
    disabled: true,
  });

  columnMenuItems.push(
    {
      name: "Format",
      cssClasses: ["format-main-container"],
    },
    "separator"
  );

  columnMenuItems.push({
    name: "Numeric Values",
    subMenu: [
      {
        name: "Full Number",
        action: () => onNumberFormatChange("full"),
      },
      {
        name: "In K",

        action: () => onNumberFormatChange("thousand"),
      },
      {
        name: "In Mn",
        action: () => onNumberFormatChange("million"),
      },
      {
        name: "In Bn",
        action: () => onNumberFormatChange("billion"),
      },
    ],
    disabled: !onFontSizeChange,
  });
  columnMenuItems.push({
    name: "Font Size",
    subMenu: [
      {
        name: "Small Font",
        action: () => onFontSizeChange("small"),
      },
      {
        name: "Medium Font",

        action: () => onFontSizeChange("medium"),
      },
      {
        name: "Large Font",
        action: () => onFontSizeChange("large"),
      },
    ],
    disabled: !onNumberFormatChange,
  });

  return columnMenuItems;
};

const SortableColumnItem = ({
  column,
  level,
  renderFn,
  dragIconClass,
  onToggle,
  ...props
}) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: column.colId,
  });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
    // background: isDragging ? '#f0f0f0' : undefined,
    zIndex: isDragging ? 100 : undefined,
  };
  return (
    <div ref={setNodeRef} style={style}>
      {renderFn({
        column,
        level,
        dragProps: { ...attributes, ...listeners },
        dragIconClass,
        onToggle,
      })}
    </div>
  );
};

export const Columns = forwardRef((props, ref) => {
  const [searchText, setSearchText] = useState("");
  const [collapsedScrollable, setCollapsedScrollable] = useState(false);
  const [collapsedColumn, setCollapsedcolumn] = useState(false);
  const [frozenColumn, setFrozenColumn] = useState([]);
  const [scrollableColumn, setScrollableColumn] = useState([]);
  const [filteredFrozenColumns, setFilteredFrozenColumns] = useState([]);
  const [filteredScrollableColumns, setFilteredScrollableColumns] = useState(
    []
  );
  const [allColumnVisibility, setAllColumnvisisbility] = useState(true);
  const [mainChecked, setMainChecked] = useState(true);
  const [collapsedScrollColumns, setCollapsedScrollColumns] = useState({});
  const [collapsedFrozenColumns, setCollapsedFrozenColumns] = useState({});
  const [openSaveViewModal, setOpenSaveViewModal] = useState(false);
  const [isDefaultView, setIsDefaultView] = useState(false);
  const [selectedViewType, setSelectedViewType] = useState("global");
  const [savedViewsOptions, setSavedViewsOptions] = useState(
    props?.savedViewsOptions || []
  );
  const [filteredSavedViewsOptions, setFilteredSavedViewsOptions] = useState(
    props?.savedViewsOptions || []
  );
  const [currentSaveViewOptions, setCurrentSaveViewOptions] = useState([]);
  const [selectedSavedView, setSelectedSavedView] = useState(null);
  const [inputValue, setInputValue] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [openSaveViewMenu, setOpenSaveViewMenu] = useState(false);
  const [selectedBadge, setSelectedBadge] = useState("All");
  const [isEditView, setIsEditView] = useState(false);
  const [editedView, setEditedView] = useState(null);
  const [saveViewSearchText, setSaveViewSearchText] = useState("");
  const [openDeletePrompt, setOpenDeletePrompt] = useState(false);
  const [deleteView, setDeleteView] = useState(null);
  const [selectedView, setSelectedView] = useState(null);
  const isColumnPinnedRef = useRef(false);

  useEffect(() => {
    if (props?.savedViewsOptions?.length > 0) {
      // Create options for Select: { label: viewName, value: viewName }
      const options = props?.savedViewsOptions.map((view) => ({
        label: view.viewName,
        value: view.viewName,
        isDisabled: view?.isDisabled,
      }));
      setCurrentSaveViewOptions(options);
      setSavedViewsOptions(props?.savedViewsOptions);
      setFilteredSavedViewsOptions(props?.savedViewsOptions);
    }
  }, [props?.savedViewsOptions]);

  const getColumnDefs = useCallback((columns) => {
    return columns.map((column) => {
      if (column.children) {
        const updatedChildren = getColumnDefs(column.children);
        const allChildrenHidden = updatedChildren.every(
          (child) => child.hide === true
        );
        return {
          ...column,
          children: updatedChildren,
          hide: allChildrenHidden,
        };
      }
      return column;
    });
  }, []);

  const updateColumnState = useCallback(() => {
    const getColumnState = (columns) => {
      return columns.map((column) => {
        // Handle the parent column definition
        const columnState = {
          colId: column.colId || column.field || column.headerName,
          headerName: column.headerName || column.field || "N/A",
          isVisible: !column?.hide,
          isPinned: column.pinned ? true : false,
          children:
            column?.children?.length > 0
              ? getColumnState(column.children)
              : null, // Recursively handle child columns
          disabled: column?.disableColumnCheckboxInSettings,
        };

        return columnState;
      });
    };

    const columnDefs = getColumnDefs(
      ref?.current?.api?.getColumnDefs() || props.column
    );

    // Call the function to get the column state
    const columnState = getColumnState(columnDefs);
    const { frozColumn, scrollColumn } = (columnState || []).reduce(
      (acc, column) => {
        if (column.isPinned) {
          acc.frozColumn.push(column);
        } else {
          acc.scrollColumn.push(column);
        }
        return acc;
      },
      { frozColumn: [], scrollColumn: [] }
    );
    setFrozenColumn(frozColumn);
    setFilteredFrozenColumns(frozColumn);
    setScrollableColumn(scrollColumn);
    setFilteredScrollableColumns(scrollColumn);
  }, [getColumnDefs, ref, props.column]);

  const debouncedUpdateColumnState = useMemo(
    () => debounce(updateColumnState, 100),
    [updateColumnState]
  );

  useEffect(() => {
    if (
      props.showMenu || // Always update when menu is shown
      isColumnPinnedRef.current
    ) {
      isColumnPinnedRef.current = false;

      updateColumnState();

      const onColumnPinned = () => {
        isColumnPinnedRef.current = true;
        debouncedUpdateColumnState();
      };

      if (ref?.current) {
        ref.current?.api?.addEventListener("columnPinned", onColumnPinned);
        ref.current?.api?.addEventListener("columnMoved", onColumnPinned);
        ref.current?.api?.addEventListener("columnVisible", onColumnPinned);
      }

      return () => {
        if (ref?.current) {
          ref.current?.api?.removeEventListener("columnPinned", onColumnPinned);
          ref.current?.api?.removeEventListener("columnMoved", onColumnPinned);
          ref.current?.api?.removeEventListener(
            "columnVisible",
            onColumnPinned
          );
        }
      };
    }
  }, [props.showMenu]);

  const [frozenColumnOrder, setFrozenColumnOrder] = useState([]);
  const [scrollableColumnOrder, setScrollableColumnOrder] = useState([]);

  // DnD sensors
  const sensors = useSensors(useSensor(MouseSensor), useSensor(TouchSensor));

  const getAllColumnIds = (columns) => {
    let ids = [];
    columns.forEach((col) => {
      ids.push(col.colId);
      if (col.children && col.children.length > 0) {
        ids = ids.concat(getAllColumnIds(col.children));
      }
    });
    return ids;
  };

  useEffect(() => {
    setFrozenColumnOrder(getAllColumnIds(filteredFrozenColumns));
    setScrollableColumnOrder(getAllColumnIds(filteredScrollableColumns));
  }, [filteredFrozenColumns, filteredScrollableColumns]);

  const handleSearchChange = (e) => {
    const searchText = e.target.value.toLowerCase();

    const filterColumns = (columns, searchText) => {
      return columns
        .map((column) => {
          // Check if the current column matches the search text
          const matches = column.headerName.toLowerCase().includes(searchText);

          // If the column has children, filter them recursively
          const filteredChildren = column.children
            ? filterColumns(column.children, searchText)
            : null;

          // Include the column if it matches or any of its children match
          if (matches || filteredChildren?.length > 0) {
            return {
              ...column,
              children: filteredChildren,
              isVisible: column.isVisible,
            };
          }
          return null;
        })
        .filter(Boolean);
    };

    const filteredFrozenColumns = filterColumns(frozenColumn, searchText);
    const filteredScrollableColumns = filterColumns(
      scrollableColumn,
      searchText
    );

    setSearchText(searchText);
    setFilteredFrozenColumns(filteredFrozenColumns);
    setFilteredScrollableColumns(filteredScrollableColumns);
  };

  useEffect(() => {
    const isAnyScrollableColumnVisible = filteredScrollableColumns.some(
      (column) => {
        if (column.children) {
          return column.children.some((child) => child.isVisible);
        }
        return column.isVisible;
      }
    );
    const isAnyFrozenColumnVisible = filteredFrozenColumns.some((column) => {
      if (column.children) {
        return column.children.some((child) => child.isVisible);
      }
      return column.isVisible;
    });
    setMainChecked(isAnyScrollableColumnVisible);
    setAllColumnvisisbility(
      isAnyFrozenColumnVisible || isAnyScrollableColumnVisible
    );
  }, [filteredFrozenColumns, filteredScrollableColumns]);

  // Handle visibility toggle for columns
  const toggleColumnVisibilityFrozen = (colId) => {
    const updateChildrenVisibility = (columns, parentVisibility = null) =>
      columns.map((column) => {
        const updatedChildren = column.children
          ? updateChildrenVisibility(column.children, parentVisibility)
          : null;
        ref?.current?.columnApi?.setColumnVisible(
          column.colId,
          parentVisibility
        );
        return {
          ...column,
          isVisible: parentVisibility,
          children: updatedChildren,
        };
      });

    const updateVisibility = (columns, parentVisibility = null) =>
      columns.map((column) => {
        // If the column matches the colId, toggle its visibility
        if (column.colId === colId) {
          const newVisibility =
            parentVisibility !== null ? parentVisibility : !column.isVisible;

          // Update children visibility if it's a parent toggle
          const updatedChildren = column.children
            ? updateChildrenVisibility(column.children, newVisibility)
            : null;

          // Reflect visibility change in grid API
          ref?.current?.columnApi?.setColumnVisible(
            column.colId,
            newVisibility
          );

          return {
            ...column,
            isVisible: newVisibility,
            children: updatedChildren,
          };
        }

        // If it doesn't match, process children if they exist
        if (column.children) {
          const updatedChildren = updateVisibility(column.children);

          // Update parent's visibility based on children's visibility
          const isAnyChildVisible = updatedChildren.some(
            (child) => child.isVisible
          );
          ref?.current?.columnApi?.setColumnVisible(
            column.colId,
            isAnyChildVisible
          );

          return {
            ...column,
            isVisible: isAnyChildVisible,
            children: updatedChildren,
          };
        }

        return column; // No changes for unmatched columns without children
      });

    // Update the state with the new visibility
    const updatedColumns = updateVisibility(filteredFrozenColumns);
    setFilteredFrozenColumns(updatedColumns);
    setFrozenColumn((prev) => {
      const updatedMap = Object.fromEntries(
        updatedColumns.map((col) => [col.colId, col])
      );
      const merged = prev.map((col) =>
        updatedMap[col.colId] ? updatedMap[col.colId] : col
      );
      const prevColIds = new Set(prev.map((col) => col.colId));
      const newCols = updatedColumns.filter(
        (col) => !prevColIds.has(col.colId)
      );
      return [...merged, ...newCols];
    });
  };

  const toggleColumnVisibilityScroll = (colId) => {
    const updateChildrenVisibility = (columns, parentVisibility = null) =>
      columns.map((column) => {
        const updatedChildren = column.children
          ? updateChildrenVisibility(column.children, parentVisibility)
          : null;
        ref?.current?.columnApi?.setColumnVisible(
          column.colId,
          parentVisibility
        );
        return {
          ...column,
          isVisible: parentVisibility,
          children: updatedChildren,
        };
      });

    const updateVisibility = (columns, parentVisibility = null) =>
      columns.map((column) => {
        // If the column matches the colId, toggle its visibility
        if (column.colId === colId) {
          const newVisibility =
            parentVisibility !== null ? parentVisibility : !column.isVisible;

          // Update children visibility if it's a parent toggle
          const updatedChildren = column.children
            ? updateChildrenVisibility(column.children, newVisibility)
            : null;

          // Reflect visibility change in grid API
          ref?.current?.columnApi?.setColumnVisible(
            column.colId,
            newVisibility
          );

          return {
            ...column,
            isVisible: newVisibility,
            children: updatedChildren,
          };
        }

        // If it doesn't match, process children if they exist
        if (column.children) {
          const updatedChildren = updateVisibility(column.children);

          // Update parent's visibility based on children's visibility
          const isAnyChildVisible = updatedChildren.some(
            (child) => child.isVisible
          );
          ref?.current?.columnApi?.setColumnVisible(
            column.colId,
            isAnyChildVisible
          );

          return {
            ...column,
            isVisible: isAnyChildVisible,
            children: updatedChildren,
          };
        }

        return column; // No changes for unmatched columns without children
      });

    // Update the state with the new visibility
    const updatedColumns = updateVisibility(filteredScrollableColumns);
    setFilteredScrollableColumns(updatedColumns);
    setScrollableColumn((prev) => {
      const updatedMap = Object.fromEntries(
        updatedColumns.map((col) => [col.colId, col])
      );
      const merged = prev.map((col) =>
        updatedMap[col.colId] ? updatedMap[col.colId] : col
      );
      const prevColIds = new Set(prev.map((col) => col.colId));
      const newCols = updatedColumns.filter(
        (col) => !prevColIds.has(col.colId)
      );
      return [...merged, ...newCols];
    });
  };

  const toggleScrollableCollapse = (e) => {
    e.stopPropagation();
    setCollapsedScrollable(!collapsedScrollable);
  };

  const toggleColumnCollapse = (e) => {
    e.stopPropagation();
    setCollapsedcolumn(!collapsedColumn);
  };

  const onMainCheckboxChange = () => {
    // Toggle the main checkbox state
    setMainChecked((prev) => !prev);

    // Helper function to recursively update visibility for all columns and children
    const updateVisibility = (columns, visibility) => {
      return columns.map((column) => {
        // Set column visibility
        ref?.current?.columnApi?.setColumnVisible(column.colId, visibility);

        // If the column has children, recursively update their visibility
        if (column.children) {
          updateVisibility(column.children, visibility);
        }

        // Return the updated column with new visibility state
        return {
          ...column,
          isVisible: visibility,
          children: column.children
            ? updateVisibility(column.children, visibility)
            : null,
        };
      });
    };

    // Update the visibility for all columns (parent + children)
    const updatedColumns = updateVisibility(
      filteredScrollableColumns,
      !mainChecked
    );
    setFilteredScrollableColumns(updatedColumns);
    setScrollableColumn((prev) => {
      const updatedMap = Object.fromEntries(
        updatedColumns.map((col) => [col.colId, col])
      );
      const merged = prev.map((col) =>
        updatedMap[col.colId] ? updatedMap[col.colId] : col
      );
      const prevColIds = new Set(prev.map((col) => col.colId));
      const newCols = updatedColumns.filter(
        (col) => !prevColIds.has(col.colId)
      );
      return [...merged, ...newCols];
    });
  };

  const onAllColumnCheckBoxChange = () => {
    setAllColumnvisisbility((prev) => !prev); // Toggle visibility state
    setMainChecked(!allColumnVisibility);
    // Helper function to recursively update visibility for all columns and children
    const updateColumnVisibility = (columns, visibility) => {
      return columns.map((column) => {
        // Set column visibility in ag-Grid API
        ref?.current?.columnApi?.setColumnVisible(column.colId, visibility);

        // If column has children, recursively update their visibility
        if (column.children) {
          updateColumnVisibility(column.children, visibility);
        }

        // Return the updated column with new visibility state
        return {
          ...column,
          isVisible: visibility,
          children: column.children
            ? updateColumnVisibility(column.children, visibility)
            : null,
        };
      });
    };

    // Update visibility for frozen columns
    const updatedFrozenColumns = updateColumnVisibility(
      filteredFrozenColumns,
      !allColumnVisibility
    );

    const updatedScrollableColumns = updateColumnVisibility(
      filteredScrollableColumns,
      !allColumnVisibility
    );

    // Update the state with the new visibility for all columns
    setFilteredFrozenColumns(updatedFrozenColumns);
    setFilteredScrollableColumns(updatedScrollableColumns);
    setFrozenColumn((prev) => {
      const updatedMap = Object.fromEntries(
        updatedFrozenColumns.map((col) => [col.colId, col])
      );
      const merged = prev.map((col) =>
        updatedMap[col.colId] ? updatedMap[col.colId] : col
      );
      const prevColIds = new Set(prev.map((col) => col.colId));
      const newCols = updatedFrozenColumns.filter(
        (col) => !prevColIds.has(col.colId)
      );
      return [...merged, ...newCols];
    });
    setScrollableColumn((prev) => {
      const updatedMap = Object.fromEntries(
        updatedScrollableColumns.map((col) => [col.colId, col])
      );
      const merged = prev.map((col) =>
        updatedMap[col.colId] ? updatedMap[col.colId] : col
      );
      const prevColIds = new Set(prev.map((col) => col.colId));
      const newCols = updatedScrollableColumns.filter(
        (col) => !prevColIds.has(col.colId)
      );
      return [...merged, ...newCols];
    });
  };

  const toggleScrollColumnCollapse = (colId) => {
    setCollapsedScrollColumns((prev) => ({
      ...prev,
      [colId]: !prev[colId], // Toggle collapse state for the specific column
    }));
  };

  const toggleFrozenColumnCollapse = (colId) => {
    setCollapsedFrozenColumns((prev) => ({
      ...prev,
      [colId]: !prev[colId], // Toggle collapse state for the specific frozen column
    }));
  };

  const reorderColDefsByColId = (colDefs, newOrder, type = "scrollable") => {
    // Helper to recursively reorder columns and their children
    const reorder = (columns) => {
      // Filter columns by type
      let filteredCols = [];
      if (type === "frozen") {
        filteredCols = columns.filter((col) => col.pinned === "left");
      } else {
        filteredCols = columns.filter((col) => col.pinned !== "left");
      }
      // Sort and map recursively
      const sorted = [...filteredCols]
        .filter((col) =>
          newOrder.includes(col.colId || col.field || col.headerName)
        )
        .sort(
          (a, b) =>
            newOrder.indexOf(a.colId || a.field || a.headerName) -
            newOrder.indexOf(b.colId || b.field || b.headerName)
        )
        .map((col) => {
          if (col.children && col.children.length > 0) {
            return {
              ...col,
              children: reorder(col.children),
            };
          }
          return col;
        });
      return sorted;
    };

    // Get the other type columns to append at the end
    let otherCols = [];
    if (type === "frozen") {
      otherCols = colDefs.filter((col) => col.pinned !== "left");
    } else {
      otherCols = colDefs.filter((col) => col.pinned === "left");
    }

    return [...otherCols, ...reorder(colDefs)];
  };

  const handleFrozenDragEnd = (event) => {
    const { active, over } = event;
    if (active.id !== over?.id) {
      const oldIndex = frozenColumnOrder.indexOf(active.id);
      const newIndex = frozenColumnOrder.indexOf(over.id);
      const newOrder = arrayMove(frozenColumnOrder, oldIndex, newIndex);
      setFrozenColumnOrder(newOrder);
      const reordered = newOrder
        .map((id) => frozenColumn.find((c) => c.colId === id))
        .filter(Boolean);
      setFrozenColumn(reordered);
      setFilteredFrozenColumns(reordered);
      let colDefs = ref?.current?.api?.getColumnDefs();
      if (colDefs) {
        const newColDefs = reorderColDefsByColId(colDefs, newOrder, "frozen");
        ref?.current?.api?.setColumnDefs(newColDefs);
      }
    }
  };
  const handleScrollableDragEnd = (event) => {
    const { active, over } = event;
    if (active.id !== over?.id) {
      const oldIndex = scrollableColumnOrder.indexOf(active.id);
      const newIndex = scrollableColumnOrder.indexOf(over.id);
      const newOrder = arrayMove(scrollableColumnOrder, oldIndex, newIndex);
      setScrollableColumnOrder(newOrder);
      const reordered = newOrder
        .map((id) => filteredScrollableColumns.find((c) => c.colId === id))
        .filter(Boolean);
      // const reordered = moveColumnById([...filteredScrollableColumns], active.id, over.id);
      setScrollableColumn(reordered);
      setFilteredScrollableColumns(reordered);
      let colDefs = ref?.current?.api?.getColumnDefs();
      if (colDefs) {
        const newColDefs = reorderColDefsByColId(
          colDefs,
          newOrder,
          "scrollable"
        );
        ref?.current?.api?.setColumnDefs(newColDefs);
      }
    }
  };

  // const moveColumnById = (columns, fromId, toId) => {
  //   // Find and remove the column with fromId
  //   let removed, parentFrom, indexFrom;
  //   const remove = (cols, parent = null) => {
  //     for (let i = 0; i < cols.length; i++) {
  //       if (cols[i].colId === fromId) {
  //         removed = cols.splice(i, 1)[0];
  //         parentFrom = parent;
  //         indexFrom = i;
  //         return true;
  //       }
  //       if (cols[i].children) {
  //         if (remove(cols[i].children, cols[i])) return true;
  //       }
  //     }
  //     return false;
  //   };
  //   remove(columns);

  //   // Find where to insert
  //   const insert = (cols, toId) => {
  //     for (let i = 0; i < cols.length; i++) {
  //       if (cols[i].colId === toId) {
  //         cols.splice(i, 0, removed);
  //         return true;
  //       }
  //       if (cols[i].children) {
  //         if (insert(cols[i].children, toId)) return true;
  //       }
  //     }
  //     return false;
  //   };
  //   insert(columns, toId);

  //   return columns;
  // };

  const updateColumnDefs = (order, type, movedId, pinDirection) => {
    let colDefs = ref?.current?.api?.getColumnDefs();
    if (!colDefs) return;

    const newColDefs = reorderColDefsByColId(colDefs, order, type);
    if (movedId) {
      const colDefToUpdate = newColDefs.find((c) => c.colId === movedId);
      if (colDefToUpdate) {
        colDefToUpdate.pinned = pinDirection;
      }
    }
    ref?.current?.api?.setColumnDefs(newColDefs);
  };

  const handleDragEnd = (event) => {
    const { active, over } = event;
    if (!over) return;
    const activeId = active.id;
    const overId = over.id;

    const isFrozenSource = frozenColumnOrder.includes(activeId);
    const isFrozenTarget = frozenColumnOrder.includes(overId);

    // If dragging within same list
    if (isFrozenSource && isFrozenTarget) {
      const oldIndex = frozenColumnOrder.indexOf(activeId);
      const newIndex = frozenColumnOrder.indexOf(overId);
      const newOrder = arrayMove(frozenColumnOrder, oldIndex, newIndex);
      setFrozenColumnOrder(newOrder);
      const reordered = newOrder
        .map((id) => frozenColumn.find((c) => c.colId === id))
        .filter(Boolean);
      setFrozenColumn(reordered);
      setFilteredFrozenColumns(reordered);
      updateColumnDefs(newOrder, "frozen");
    } else if (!isFrozenSource && !isFrozenTarget) {
      const oldIndex = scrollableColumnOrder.indexOf(activeId);
      const newIndex = scrollableColumnOrder.indexOf(overId);
      const newOrder = arrayMove(scrollableColumnOrder, oldIndex, newIndex);
      setScrollableColumnOrder(newOrder);
      const reordered = newOrder
        .map((id) => filteredScrollableColumns.find((c) => c.colId === id))
        .filter(Boolean);
      setScrollableColumn(reordered);
      setFilteredScrollableColumns(reordered);
      updateColumnDefs(newOrder, "scrollable");
    } else {
      // Handle move between frozen <--> scrollable
      // if (isFrozenSource) {
      //   // Remove from frozen
      //   const newFrozen = frozenColumnOrder.filter(id => id !== activeId);
      //   const updatedFrozen = newFrozen.map(id => frozenColumn.find(c => c.colId === id)).filter(Boolean);
      //   setFrozenColumnOrder(newFrozen);
      //   setFrozenColumn(updatedFrozen);
      //   setFilteredFrozenColumns(updatedFrozen);

      //   // Add to scrollable
      //   const insertAt = scrollableColumnOrder.indexOf(overId);
      //   const newScrollable = [...scrollableColumnOrder];
      //   newScrollable.splice(insertAt, 0, activeId);
      //   const newScrollableCols = newScrollable.map(id =>
      //     [...filteredFrozenColumns, ...filteredScrollableColumns].find(c => c.colId === id)
      //   ).filter(Boolean);
      //   setScrollableColumnOrder(newScrollable);
      //   setScrollableColumn(newScrollableCols);
      //   setFilteredScrollableColumns(newScrollableCols);
      //   updateColumnDefs(newScrollable, "scrollable", activeId, null); // unpin
      // }
      if (isFrozenSource) {
        const updatedFrozenOrder = frozenColumnOrder.filter(
          (id) => id !== activeId
        );
        const updatedFrozenCols = updatedFrozenOrder
          .map((id) => frozenColumn.find((c) => c.colId === id))
          .filter(Boolean);
        setFrozenColumnOrder(updatedFrozenOrder);
        setFrozenColumn(updatedFrozenCols);
        setFilteredFrozenColumns(updatedFrozenCols);

        // Determine target insert index (safe fallback if overId is not in target list)
        const overIndex = scrollableColumnOrder.findIndex(
          (id) => id === overId
        );
        const insertAt =
          overIndex === -1 ? scrollableColumnOrder.length : overIndex;
        // Add to scrollable
        const newScrollableOrder = [...scrollableColumnOrder];
        newScrollableOrder.splice(insertAt, 0, activeId);

        const allColumns = [
          ...filteredFrozenColumns,
          ...filteredScrollableColumns,
        ];
        const updatedScrollableCols = newScrollableOrder
          .map((id) => allColumns.find((c) => c.colId === id))
          .filter(Boolean);
        setScrollableColumnOrder(newScrollableOrder);
        setScrollableColumn(updatedScrollableCols);
        setFilteredScrollableColumns(updatedScrollableCols);

        updateColumnDefs(newScrollableOrder, "scrollable", activeId, null); // unpin
      } else {
        // Remove from scrollable
        const newScrollable = scrollableColumnOrder.filter(
          (id) => id !== activeId
        );
        const updatedScrollable = newScrollable
          .map((id) => scrollableColumn.find((c) => c.colId === id))
          .filter(Boolean);
        setScrollableColumnOrder(newScrollable);
        setScrollableColumn(updatedScrollable);
        setFilteredScrollableColumns(updatedScrollable);

        // Add to frozen
        const overIndex = frozenColumnOrder.findIndex((id) => id === overId);
        const insertAt =
          overIndex === -1 ? frozenColumnOrder.length : overIndex;
        const newFrozen = [...frozenColumnOrder];
        newFrozen.splice(insertAt, 0, activeId);
        const newFrozenCols = newFrozen
          .map((id) =>
            [...filteredFrozenColumns, ...filteredScrollableColumns].find(
              (c) => c.colId === id
            )
          )
          .filter(Boolean);
        setFrozenColumnOrder(newFrozen);
        setFrozenColumn(newFrozenCols);
        setFilteredFrozenColumns(newFrozenCols);
        updateColumnDefs(newFrozen, "frozen", activeId, "left"); // pin left
      }
    }
  };

  const renderScrollColumn = (column, level = 0) => {
    const isCollapsed = collapsedScrollColumns[column.colId] || false;
    return (
      <SortableColumnItem
        key={column.colId}
        column={column}
        level={level}
        renderFn={({ column, level, dragProps, dragIconClass, onToggle }) => (
          <>
            <div
              className="table-setting-scroll-inner-column"
              style={{ marginLeft: `${level * 20}px` }}
            >
              {Array.isArray(column.children) && column.children.length > 0 && (
                <IconButton
                  onClick={(e) => {
                    e.stopPropagation();
                    toggleScrollColumnCollapse(column.colId);
                  }}
                  style={{ padding: "0px" }}
                >
                  {isCollapsed ? (
                    <KeyboardArrowRightIcon />
                  ) : (
                    <KeyboardArrowUpIcon />
                  )}
                </IconButton>
              )}
              <Checkbox
                checked={column.isVisible}
                onChange={() => toggleColumnVisibilityScroll(column.colId)}
                disabled={column.disabled}
              />
              <span
                {...dragProps}
                style={{ cursor: "grab", display: "inline-flex" }}
              >
                <DragIndicator className="table-setting-scroll-columns-list-drag-icon" />
              </span>
              {column.headerName.charAt(0).toUpperCase() +
                column.headerName.slice(1)}
            </div>
            {Array.isArray(column.children) &&
              column.children.length > 0 &&
              !isCollapsed && (
                <div
                  style={{
                    marginLeft: "20px",
                    display: "flex",
                    flexDirection: "column",
                    gap: "4px",
                    marginTop: "4px",
                  }}
                >
                  {column.children.map((child) => (
                    <div key={child.colId}>
                      {renderScrollColumn(child, level + 1)}
                    </div>
                  ))}
                </div>
              )}
          </>
        )}
        dragIconClass="table-setting-scroll-columns-list-drag-icon"
        onToggle={toggleScrollColumnCollapse}
      />
    );
  };

  const renderFrozencolumn = (column, level = 0) => {
    const isCollapsed = collapsedFrozenColumns[column.colId] || false;
    return (
      <SortableColumnItem
        key={column.colId}
        column={column}
        level={level}
        renderFn={({ column, level, dragProps, dragIconClass, onToggle }) => (
          <>
            <div
              className="table-setting-frozen-columns-list-item"
              style={{ marginLeft: `${level * 20}px` }}
            >
              {Array.isArray(column.children) && column.children.length > 0 && (
                <IconButton
                  onClick={(e) => {
                    e.stopPropagation();
                    toggleFrozenColumnCollapse(column.colId);
                  }}
                  style={{ padding: "0px" }}
                >
                  {isCollapsed ? (
                    <KeyboardArrowRightIcon />
                  ) : (
                    <KeyboardArrowUpIcon />
                  )}
                </IconButton>
              )}
              <Checkbox
                checked={column.isVisible}
                onChange={() => toggleColumnVisibilityFrozen(column.colId)}
                disabled={column?.disabled}
              />
              <span
                {...dragProps}
                style={{ cursor: "grab", display: "inline-flex" }}
              >
                <DragIndicator className="table-setting-frozen-columns-list-drag-icon" />
              </span>
              {column.headerName.charAt(0).toUpperCase() +
                column.headerName.slice(1)}
            </div>
            {Array.isArray(column.children) &&
              column.children.length > 0 &&
              !isCollapsed && (
                <div
                  style={{
                    marginLeft: "20px",
                    display: "flex",
                    flexDirection: "column",
                    gap: "4px",
                    marginTop: "4px",
                  }}
                >
                  {column.children.map((child) => (
                    <div key={child.colId}>
                      {renderFrozencolumn(child, level + 1)}
                    </div>
                  ))}
                </div>
              )}
          </>
        )}
        dragIconClass="table-setting-frozen-columns-list-drag-icon"
        onToggle={toggleFrozenColumnCollapse}
      />
    );
  };

  const handleSaveAndApply = () => {
    if (isEditView) {
      let newView = {
        ...editedView,
        viewName: inputValue,
        viewType: selectedViewType,
        isDefaultView: isDefaultView,
        isActive: false,
      };
      props?.handleEditSaveView(newView, editedView);
      if (!props?.isSavingViewLoading) {
        setIsEditView(false);
        setEditedView(null);
        setOpenSaveViewModal(false);
        setInputValue("");
        setSelectedViewType("global");
        setIsDefaultView(false);
      }
      return;
    }
    let newView = {
      viewName: inputValue,
      viewType: selectedViewType,
      isDefaultView: isDefaultView,
      isActive: true,
    };
    setSavedViewsOptions((prev) => [
      ...prev.map((view) => ({ ...view, isActive: false })),
      newView,
    ]);
    setFilteredSavedViewsOptions((prev) => [
      ...prev.map((view) => ({ ...view, isActive: false })),
      newView,
    ]);
    props?.handleSaveAndApply?.(newView, selectedSavedView?.value);
  };

  useEffect(() => {
    if (!props?.isSavingViewLoading) {
      setOpenSaveViewModal(false);
      setSelectedSavedView(null);
      setInputValue("");
      setSelectedViewType("global");
      setIsDefaultView(false);
      setOpenDeletePrompt(false);
      setDeleteView(null);
      setEditedView(null);
    }
  }, [props?.isSavingViewLoading]);

  const handleEditView = (view, e) => {
    e.stopPropagation();
    e.preventDefault();
    setIsEditView(true);
    setOpenSaveViewModal(true);
    setInputValue(view.viewName);
    setSelectedViewType(view.viewType);
    setIsDefaultView(view.isDefaultView);
    setEditedView(view);
  };

  const handleCloseSaveViewModal = () => {
    setOpenSaveViewModal(false);
    setSelectedSavedView(null);
    setInputValue("");
    setSelectedViewType("global");
    setIsDefaultView(false);
  };

  const handleSaveViewSearchChange = (e) => {
    setSaveViewSearchText(e.target.value);
    const filteredViews = savedViewsOptions.filter((view) =>
      view.viewName.toLowerCase().includes(e.target.value.toLowerCase())
    );
    setFilteredSavedViewsOptions(filteredViews);
  };

  const handleDeleteView = (view, e) => {
    e.stopPropagation();
    e.preventDefault();
    setOpenDeletePrompt(true);
    setDeleteView(view);
  };

  useEffect(() => {
    if (!props?.isDeleteViewLoading) {
      setOpenDeletePrompt(false);
    }
  }, [props?.isDeleteViewLoading]);

  const handleSaveViewClick = (view) => {
    setFilteredSavedViewsOptions((prev) =>
      prev.map((item) => {
        if (item.viewName === view.viewName) {
          return {
            ...item,
            isActive: true,
          };
        }
        return {
          ...item,
          isActive: false,
        };
      })
    );
    setSelectedView(view);
  }

  return (
    <div className="table-setting-columns-settings">
      {props?.isSaveViewEnabled && (
        <div className="table-setting-save-view-container">
          {savedViewsOptions.length === 0 ? (
            <div className="save-view-icon-title">
              <img src={saveViewIcon} alt="save-view-icon" />
              <span className="save-view-title">No views saved yet</span>
            </div>
          ) : (
            <div className="save-view-container-active-view">
              <Badge
                label={`${
                  savedViewsOptions.find((view) => view.isActive)?.viewName ||
                  "Not Applicable"
                }`}
                variant="stroke"
                color="success"
              />
              <Button
                icon={
                  openSaveViewMenu ? (
                    <KeyboardArrowUpIcon />
                  ) : (
                    <KeyboardArrowDownIcon />
                  )
                }
                variant="tertiary"
                size="small"
                onClick={() => setOpenSaveViewMenu(!openSaveViewMenu)}
              />
            </div>
          )}
          <Button
            variant="tertiary"
            size="small"
            onClick={() => setOpenSaveViewModal(true)}
          >
            Save View
          </Button>
        </div>
      )}
      {openSaveViewMenu && (
        <div className="save-view-menu">
          <div className="save-view-menu-title">
            <span>Saved views</span>
            <div className="save-view-menu-default-view">
              <img src={defaultViewActiveIcon} alt="default-view-icon" />
              <span className="save-view-menu-default-view-text">Default</span>
            </div>
          </div>
          <div className="save-view-menu-view-type">
            <Badge
              label={"All"}
              variant="stroke"
              color={selectedBadge === "All" ? "info" : "default"}
              onClick={() => {
                setSelectedBadge("All");
                setFilteredSavedViewsOptions([...savedViewsOptions]);
              }}
              size="small"
            />
            <Badge
              label={"Global"}
              variant="stroke"
              color={selectedBadge === "Global" ? "info" : "default"}
              onClick={() => {
                setSelectedBadge("Global");
                setFilteredSavedViewsOptions(
                  savedViewsOptions.filter((view) => view.viewType === "global")
                );
              }}
              size="small"
            />
            <Badge
              label={"Personal"}
              variant="stroke"
              color={selectedBadge === "Personal" ? "info" : "default"}
              onClick={() => {
                setSelectedBadge("Personal");
                setFilteredSavedViewsOptions(
                  savedViewsOptions.filter(
                    (view) => view.viewType === "personal"
                  )
                );
              }}
              size="small"
            />
          </div>
          <div className="save-view-menu-search-container">
            <Input
              placeholder="Search here..."
              leftIcon={<SearchIcon />}
              value={saveViewSearchText}
              onChange={handleSaveViewSearchChange}
            />
          </div>
          <div className="save-view-menu-view-list-container">
            {filteredSavedViewsOptions.length > 0 &&
              filteredSavedViewsOptions.map((view, idx) => (
                <div
                  key={view.viewName + idx}
                  className={`save-view-menu-view-list-item ${
                    view.isActive ? "active" : ""
                  }`}
                  onClick={() => handleSaveViewClick(view)}
                  tabIndex={idx === 0 ? 0 : -1}
                  role="button"
                  aria-label={`Saved view ${view.viewName}`}
                  onKeyDown={(e) => {
                    const current = e.currentTarget;
                    switch (e.key) {
                      case "Enter":
                        e.preventDefault();
                        handleSaveViewClick(view);
                        break;
                      case "ArrowDown": {
                        e.preventDefault();
                        const next = current.nextElementSibling;
                        if (next) {
                          next.focus();
                        }
                        break;
                      }
                      case "ArrowUp": {
                        e.preventDefault();
                        const prev = current.previousElementSibling;
                        if (prev) {
                          prev.focus();
                        }
                        break;
                      }
                      default:
                        break;
                    }
                  }}
                >
                  <span className="save-view-menu-view-list-item-name">
                    {view.viewName}
                  </span>
                  <div className="save-view-menu-view-list-item-actions">
                    {view?.isEditable && (
                      <img
                        src={saveViewEditIcon}
                        alt="save-view-edit-icon"
                        onClick={(e) => handleEditView(view, e)}
                      />
                    )}
                    {view?.isDeletable && (
                      <img
                        src={saveViewDeleteIcon}
                        alt="save-view-delete-icon"
                        onClick={(e) => handleDeleteView(view, e)}
                      />
                    )}
                    {view.isDefaultView ? (
                      <img
                        src={defaultViewActiveIcon}
                        alt="default-view-icon"
                        onClick={(e) => {
                          e.stopPropagation();
                          e.preventDefault();
                          props?.handleSetDefaultView(view);
                        }}
                        className="default-view-active-icon"
                      />
                    ) : (
                      <img
                        src={defaultViewIcon}
                        alt="default-view-icon"
                        onClick={(e) => {
                          e.stopPropagation();
                          e.preventDefault();
                          props?.handleSetDefaultView(view);
                        }}
                      />
                    )}
                  </div>
                </div>
              ))}
          </div>
          <hr className="save-view-menu-view-list-item-divider" />
          <div className="save-view-menu-footer">
            <Button
              variant="tertiary"
              size="medium"
              onClick={() => {
                setOpenSaveViewMenu(false);
                setFilteredSavedViewsOptions([...savedViewsOptions]);
              }}
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              size="medium"
              onClick={() => {
                props?.handleSavedViewClick?.(selectedView);
                updateColumnState();
                setOpenSaveViewMenu(false);
              }}
            >
              Apply
            </Button>
          </div>
        </div>
      )}
      <Modal
        open={openSaveViewModal}
        title={isEditView ? "Edit view" : "Save view"}
        onClose={handleCloseSaveViewModal}
        width={"422px"}
        height={"542px"}
        className="save-view-modal"
        primaryButtonLabel={props?.isSavingViewLoading ? "Saving..." : "Save"}
        secondaryButtonLabel={"Cancel"}
        onPrimaryButtonClick={handleSaveAndApply}
        onSecondaryButtonClick={handleCloseSaveViewModal}
        primaryButtonProps={{
          disabled:
            ((inputValue === "" ||
              savedViewsOptions.length === props?.maxSavedViews) &&
              selectedSavedView === null) ||
            !isViewNameUnique(
              inputValue,
              selectedViewType,
              isDefaultView,
              savedViewsOptions
            ) ||
            props?.isSavingViewLoading,
          loading: props?.isSavingViewLoading,
          iconPlacement: "right",
        }}
      >
        <div className="save-view-modal-children">
          <div className="save-view-modal-children-header">
            <span className="save-view-modal-children-header-text">{`${
              props?.maxSavedViews - savedViewsOptions.length
            }/${props?.maxSavedViews} views remaining`}</span>
          </div>
          <div className="save-view-modal-children-body">
            <div className="save-view-modal-children-body-input">
              <Input
                placeholder="Enter here"
                label={"New view name"}
                value={inputValue}
                onChange={(e) => {
                  setInputValue(e.target.value);
                  setSelectedSavedView(null);
                }}
              />
            </div>
            <div className="save-view-modal-children-body-radio-group">
              <span className="save-view-modal-children-body-radio-group-text">
                View type
              </span>
              <RadioButtonGroup
                options={[
                  { label: "Global", value: "global" },
                  { label: "Personal", value: "personal" },
                ]}
                onChange={(event) => setSelectedViewType(event.target.value)}
                orientation={"row"}
                selectedOption={selectedViewType}
              />
            </div>
            <div className="save-view-modal-children-body-checkbox">
              <Checkbox
                checked={isDefaultView}
                onChange={() => setIsDefaultView(!isDefaultView)}
                label={"Make it default view"}
              />
            </div>
            <div className="save-view-modal-children-body-replace-view">
              <span>Or replace with saved view</span>
            </div>
            <div className="save-view-modal-children-body-replace-view-select">
              <Select
                label={"Replace with"}
                minWidth={"100%"}
                currentOptions={currentSaveViewOptions}
                setCurrentOptions={setCurrentSaveViewOptions}
                selectedOptions={selectedSavedView}
                setSelectedOptions={setSelectedSavedView}
                withPortal
                isDisabled={savedViewsOptions.length === 0 || inputValue !== ""}
                isOpen={isOpen}
                setIsOpen={setIsOpen}
                initialOptions={currentSaveViewOptions}
              />
            </div>
          </div>
        </div>
      </Modal>
      <Prompt
        handleClose={() => setOpenDeletePrompt(false)}
        onPrimaryButtonClick={() => props?.handleDeleteViewClick?.(deleteView)}
        onSecondaryButtonClick={() => setOpenDeletePrompt(false)}
        primaryButtonLabel="Yes,Delete"
        secondaryButtonLabel="Cancel"
        title="Delete, Are you sure?"
        variant="error"
        primaryButtonProps={{
          loading: props?.isDeleteViewLoading,
          iconPlacement: "right",
        }}
        isOpen={openDeletePrompt}
      >
        {props?.deleteViewPromptText}
      </Prompt>
      <div className="table-setting-column-search-container">
        <IconButton onClick={toggleColumnCollapse} style={{ padding: "5px" }}>
          {collapsedColumn ? (
            <KeyboardArrowRightIcon />
          ) : (
            <KeyboardArrowUpIcon />
          )}
        </IconButton>
        <Checkbox
          checked={allColumnVisibility}
          onChange={onAllColumnCheckBoxChange}
        />
        <Input
          rightIcon={<SearchIcon />}
          placeholder="Search"
          value={searchText}
          onChange={handleSearchChange}
        />
      </div>
      {!collapsedColumn && (
        <div
          className={`table-setting-column-collapse-container ${
            props?.isSaveViewEnabled ? "save-view-enabled" : ""
          }`}
        >
          {/* Frozen Columns */}
          <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
          >
            <SortableContext
              items={[...scrollableColumnOrder, ...frozenColumnOrder]}
            >
              {frozenColumn.length > 0 &&
                !(
                  frozenColumn.length === 1 &&
                  frozenColumn[0].headerName === "N/A"
                ) && (
                  <div className="table-setting-collapse-columns-container">
                    <h3>Frozen columns</h3>
                    {/* {/* <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleFrozenDragEnd}> */}
                    {/* <SortableContext items={frozenColumnOrder}> */}
                    <div className="table-setting-frozen-columns-list">
                      {filteredFrozenColumns?.map(
                        (column) =>
                          column.headerName !== "N/A" &&
                          renderFrozencolumn(column)
                      )}
                    </div>
                    {/* </SortableContext> */}
                    {/* </DndContext> */}
                  </div>
                )}
              {/* Scrollable Columns */}
              <div className="table-setting-scroll-columns-container">
                <h3>Scrollable Columns</h3>
                {/* {/* <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleScrollableDragEnd}> */}
                {/* <SortableContext items={scrollableColumnOrder}>  */}
                <div className="table-setting-scroll-main-column-list">
                  <div className="table-setting-scroll-main-column">
                    <IconButton
                      onClick={toggleScrollableCollapse}
                      style={{ padding: "0px" }}
                    >
                      {collapsedScrollable ? (
                        <KeyboardArrowRightIcon />
                      ) : (
                        <KeyboardArrowUpIcon />
                      )}
                    </IconButton>
                    <Checkbox
                      checked={mainChecked}
                      onChange={onMainCheckboxChange}
                    />
                    Main Column
                  </div>
                  <div className="table-setting-scroll-inner-column-list">
                    {!collapsedScrollable &&
                      filteredScrollableColumns?.map(
                        (column) =>
                          column.headerName !== "N/A" &&
                          renderScrollColumn(column)
                      )}
                  </div>
                </div>
                {/* </SortableContext> */}
                {/* </DndContext> */}
              </div>
            </SortableContext>
          </DndContext>
        </div>
      )}
    </div>
  );
});

export const updateFontSizeOnToolPanel = (fontSizeType) => {
  let fontSize;
  switch (fontSizeType) {
    case "small":
      fontSize = "12px";
      break;
    case "medium":
      fontSize = "14px";
      break;
    case "large":
      fontSize = "16px";
      break;
    default:
      fontSize = "14px";
  }
  return fontSize;
};

// export const formatNumber = (num, format, cellprops, item) => {
//   if (!num) return "";
//   switch (format) {
//     case "billion":
//       // Nine Zeroes for Billions
//       let billionFormat = (Math.abs(Number(num)) / 1.0e9).toFixed(2) + "B";
//       return String(billionFormat) === "0.00B" ? "0B" : billionFormat;
//     case "million":
//       // Six Zeroes for Millions
//       let millionFormat = (Math.abs(Number(num)) / 1.0e6).toFixed(2) + "M";
//       return String(millionFormat) === "0.00M" ? "0M" : millionFormat;
//     case "thousand":
//       let thousandFormat = (Math.abs(Number(num)) / 1.0e3).toFixed(2) + "K";
//       return String(thousandFormat) === "0.00K" ? "0K" : thousandFormat;
//     default:
//       return formatDefaultCase(cellprops, item);
//   }
// };

// <div style={{ paddingTop: "10px", paddingLeft: "17.5px" }}>
//             <Typography variant="body2" className="ia-scrollable">
//               Scrollable Columns
//             </Typography>
//             <div className="ia-frozen-colum">
//               {/* Main Column */}
//               <div className="ia-column">
//                 <IconButton
//                   onClick={toggleScrollableCollapse}
//                   style={{ padding: "0px" }}
//                 >
//                   {collapsedScrollable ? (
//                     <KeyboardArrowRightIcon />
//                   ) : (
//                     <KeyboardArrowUpIcon />
//                   )}
//                 </IconButton>
//                 <Checkbox
//                   checked={mainChecked}
//                   onChange={onMainCheckboxChange}
//                 />
//                 <DragIndicator className="ia-drag" />
//                 Main Column
//               </div>
//               {/* Inner Columns */}
//               {!collapsedScrollable &&
//                 filteredScrollableColumns?.map((column, index) => (
//                   <div key={index} className="ia-inner-column">
//                     <Checkbox
//                       checked={column.isVisible}
//                       onChange={() =>
//                         toggleColumnVisibilityScroll(column.colId)
//                       }
//                     />
//                     <DragIndicator className="ia-drag" />
//                     {column.headerName.charAt(0).toUpperCase() +
//                       column.headerName.slice(1)}
//                   </div>
//                 ))}
//             </div>
//           </div>
