import {
 MRT_ColumnFiltersState,
 MRT_PaginationState,
 MRT_SortingState,
 useMaterialReactTable,
 MaterialReactTable,
 MRT_ToggleFullScreenButton,
 MRT_ToggleDensePaddingButton,
 MRT_Icons,
 MRT_ToggleFiltersButton,
 createMRTColumnHelper,
 MRT_ExpandedState,
 MRT_ColumnFilterFnsState,
} from 'material-react-table';
import {
 Box,
 Button,
 Divider,
 Grid,
 IconButton,
 Menu,
 MenuItem,
 ThemeProvider,
 Typography,
 createTheme,
} from '@mui/material';
import { useEffect, useState, useContext, useMemo, memo } from 'react';
import { composePaths } from '@jsonforms/core';
import {
 JsonFormsDispatch,
 useJsonForms,
 withJsonFormsControlProps,
} from '@jsonforms/react';
import { DataContext } from '../../context/Context';
import { inputProps } from '../../interface/inputfieldProps';
import _ from 'lodash';
import ComponentWrapper from '../../common/ComponentWrapper';
import { getFieldName } from '../../permissions/getFieldName';
import { getComponentProps } from '../../common/getComponentProps';
import {
 arrayToCsv,
 download,
 updateDataHandler,
} from '../../common/fileDownloadFunction';
import { toLocaleString } from '../../common/formatUtils';
import SearchIcon from '@mui/icons-material/Search';
import { FilterList, FilterListOff, Opacity } from '@mui/icons-material';
import { ArrowDownward, ArrowUpward } from '@mui/icons-material';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
import './Table.css';
import SelectAll from '../../assets/TableIcons/SelectAll';
import ShowHideColumns from '../../assets/TableIcons/ShowHideColumns';
import FullScreen from '../../assets/TableIcons/FullScreen';
import ToggleDensity from '../../assets/TableIcons/ToggleDensity';
import Download from '../../assets/TableIcons/Download';
import { ShowHideColumnsMenu } from './ShowHideColumnsMenu';
import ListIcon from '../../assets/ListIcon';
import ExitFullScreen from '../../assets/TableIcons/ExitFullScreen';
import LeaderboardAvatar from '../../assets/LeaderboardAvatar'
import React from 'react';

export const Table = memo(function ({
 data,
 uischema,
 path,
 schema,
 renderers,
 rootSchema,
 handleChange,
}: inputProps) {
 const uischemaData = uischema.config.main;
 const ctx = useJsonForms();
 const {
  theme,
  pageName,
  permissions,
  serviceProvider,
  setFormdata,
  formData,
  locale,
  timeZone,
  dateFormat,
  dateTimeFormat,
  serverDateTimeFormat,
 } = useContext(DataContext);
 const fieldName = getFieldName(path);
 const rowIdKey  = uischemaData?.rowIdKey  || 'id';
 const parentIdKey = uischemaData?.parentIdKey || 'parentId';
 const [selectActive, setSelectActive] = useState<boolean>(false);
 const [tableData, setTableData] = useState(
  (uischemaData?.lazyLoading ? data?.data : data) || []
 );
 const [tableLoading, setTableLoading] = useState<boolean>(false);
 const [pagination, setPagination] = useState<MRT_PaginationState>({
  pageIndex: 0,
  pageSize: 10,
 });
 const [isRefetching, setIsRefetching] = useState(false);
 const [rowCount, setRowCount] = useState(data?.meta?.totalRowCount || 50);
 const [columnFilters, setColumnFilters] = useState<MRT_ColumnFiltersState>([]);
 const [globalFilter, setGlobalFilter] = useState('');
 const [sorting, setSorting] = useState<MRT_SortingState>([]);
 const [isFullScreen, setIsFullScreen] = useState(false);
 const [columnKeys, setColumnKeys] = useState({});
 const [selectRow, setSelectRow] = useState<any | null>(null);
 const [currentRow, setCurrentRow] = useState<any | null>(null);
 const [menuAnchor, setMenuAnchor] = useState(null);
 const [columnFilterModes, setColumnFilterModes] =
  useState<MRT_ColumnFilterFnsState>({});
 const [maxDepth, setMaxDepth] = useState(0);

 function getDefaultExpandedRows(rows: any[], rowIdKey: string): Record<string, boolean> {
    const expandedRows: Record<string, boolean> = {};
    rows?.forEach((row) => {
      const rowKey = row?.[rowIdKey];
      if (rowKey != null && row?.defaultExpanded) expandedRows[rowKey] = true;
    });
    return expandedRows;
  }
  const [expanded, setExpanded] = useState<MRT_ExpandedState>(() =>
  getDefaultExpandedRows((uischemaData?.lazyLoading ? data?.data : data) || [], rowIdKey)
  );

 const pageSizeList = [5, 10, 15, 20, 25, 30, 50, 100, 500];
 const maxPageSize = uischemaData?.maxPageSize || 100;
 const filteredPageSizeList = pageSizeList.filter(
  (option) => option <= maxPageSize
 );
 const dynamicStyle = React.useMemo(() => {
  return serviceProvider(
   ctx,
   {
    onClick: uischema.config?.main?.styleFunction || 'getStyle',
   },
   {
    event: { _reactName: 'onClick' },
    path,
   },
  );
 }, [data, path]);
 const componentStyle = { ...uischema.config?.style, ...dynamicStyle };
 const getData = async (parentIds?: string[]) => {
  const tableColumnConfig = tableColumnConfigFormatter();
  return await serviceProvider(
   ctx,
   {
    ...uischemaData,
    onClick: uischemaData.lazyLoadFunction || 'onPaginationChange',
   },
   {
    event: { _reactName: 'onClick' },
    path,
    ...uischemaData.additionalData,
    paramValue: {
     pagination,
     path,
     columnFilters,
     globalFilter,
     sorting,
     tableColumnConfig,
     parentIds,
     isExpandAll: expandedRowIds === 'all' ? true : false,
    },
   }
  );
 }
 const updateTableData = async (
  parentIds?: string[],
  isAppendData: boolean = false
) => {
  setTableLoading(true);
  try {
    const result = await getData(parentIds);
    if (!result?.data) {
      return;
    }
    if(isAppendData) {
      setFormdata((pre) => {
        return {
          ...pre,
          [path]: [...(pre[path] ?? []), ...result.data],
        }
      })
    }
    else {
      const pevFormData = _.cloneDeep(data?.data || data);
      setUpdatedTableData(result, pevFormData);
    }
  }
  finally {
    setTableLoading(false);
  }
 };

 const idToIndexMap = useMemo(() => {
  const map = new Map<string, number>();
  tableData?.forEach((row, index) => {
    map.set(row[rowIdKey], index);
  })
  return map;
}, [tableData, rowIdKey]);

 const columns = useMemo(
  () =>
   uischema?.elements?.map((UISchemacolumn: any, index: number) => {
    setColumnFilterModes((prev) => {
     return {
      ...prev,
      [UISchemacolumn.accessorKey]:
       columnFilterModes[UISchemacolumn.accessorKey] ||
       getDefaultOperator(UISchemacolumn?.columnFilterModeOptions),
     };
    });
    if (UISchemacolumn.columnKey) {
     setColumnKeys((pre) => ({
      ...pre,
      [UISchemacolumn.accessorKey]: UISchemacolumn.columnKey,
     }));
    }
    return convertColumn({
     data,
     uischema,
     path,
     schema,
     renderers,
     rootSchema,
     handleChange,
     UISchemacolumn,
     theme,
     serviceProvider,
     pageName,
     fieldName,
     permissions,
     ctx,
     locale,
     dateTimeFormat,
     timeZone,
     dateFormat,
     serverDateTimeFormat: UISchemacolumn?.dateFormat ?? serverDateTimeFormat,
     index,
     updateTableData,
     setColumnFilterModes,
     setColumnKeys,
     columnFilterModes,
     idToIndexMap,
     rowIdKey,
    });
   }),
  [columnFilters, idToIndexMap]
 );

 function tableColumnConfigFormatter() {
  return columnFilters.map((column) => {
   return {
    ...column,
    operator: columnFilterModes[column.id],
    key: columnKeys[column.id] || column.id,
   };
  });
 }
 const expandedRowIds: string[] | 'all' = useMemo(
  () =>
   expanded === true
    ? 'all'
    : Object.entries(expanded)
       .filter(([rowId, isExpanded]) => isExpanded)
       .map(([rowId]) => rowId),
  [expanded]
 );
 useEffect(() => {
  if (uischemaData.lazyLoading) {
   updateTableData();
  }
 }, [pagination.pageIndex, pagination.pageSize, sorting]);
 useEffect(() => {
  if (!renderTable) return;
  const rows = renderTable.getExpandedRowModel().rows;
  const maxDepth = rows.length ? Math.max(...rows.map((row) => row.depth)) : 0;
  setMaxDepth(maxDepth);
 }, [tableData]);
 useEffect(() => {
  if (!data) return;
  if (data?.data) return;
  setTableData(data);
  const rowCount = formData[`${path}_RowCount`];
  if (rowCount === undefined || rowCount === null) return;
  setRowCount(formData[`${path}_RowCount`]);
 }, [data, path, pageName]);

 const handleMove = (
  direction: string,
  event: React.MouseEvent<HTMLLIElement, MouseEvent>
 ) => {
  if (!selectRow) return;
  const rowMovement = {
   movedRowId: selectRow.original.id,
   targetRowId: currentRow.original.id,
   direction: direction,
  };
  const tableColumnConfig = tableColumnConfigFormatter();
  const pevFormData = _.cloneDeep(data?.data || data);
  setIsRefetching(true);
  serviceProvider(
   ctx,
   {
    ...uischemaData,
    onClick: uischemaData.onRowMovement || 'onRowMovement',
   },
   {
    path,
    ...uischemaData.additionalData,
    event,
    paramValue: {
     path,
     rowMovement,
     pagination,
     globalFilter,
     sorting,
     expandedRowIds,
     tableColumnConfig,
    },
   }
  ).then((res: any) => {
   if (!!!res?.data) {
    return;
   }
   setUpdatedTableData(res, pevFormData);
  });
  setSelectRow(null);
  setCurrentRow(null);
  return;
 };

 const setUpdatedTableData = (res: any, pevFormData: any[]) => {
  if (uischemaData.Selection) {
   const tableSelection = {};
   pevFormData?.map((e) => {
    if (e?.[uischemaData.selectKey || 'isSelect']) {
     tableSelection[e.id] = true;
     // setTableSelectedValue((pre) => ({ ...pre, [e.id]: true }));
    }
   });
   const actualData = res?.data || res;
   const updatedData = actualData?.map((e) => {
    if (tableSelection[e.id] || selectActive) {
     return { ...e, [uischemaData.selectKey || 'isSelect']: true };
    }
    return e;
   });
   setFormdata((pre) => {
    return {
     ...pre,
     [path]: updatedData,
     [`${path}_RowCount`]: res?.meta?.totalRowCount ?? pre[`${path}_RowCount`],
    };
   });
   setRowCount(res?.meta?.totalRowCount);
   setExpanded(getDefaultExpandedRows(updatedData, rowIdKey));
  } else {
   setFormdata((pre) => ({
    ...pre,
    [path]: res.data || [],
    [`${path}_RowCount`]: res?.meta?.totalRowCount ?? pre[`${path}_RowCount`],
   }));
   setRowCount(res.meta.totalRowCount);
   setExpanded(getDefaultExpandedRows(res.data || [], rowIdKey));
  }
  setIsRefetching(false);
  setTableLoading(false);
 };
 const handleFullScreenToggle = () => {
  setIsFullScreen((prevState) => !prevState);
 };
 const allowedFields = uischema?.elements?.map((elem) => ({
  accessorKey: elem.accessorKey,
  header: elem.header,
 }));
 const tableTheme = useMemo(
  () => createTheme(tableStyle(theme)),
  [theme.myTheme]
 );
 const generateCSV = (data) => {
  const filename = uischemaData?.filename || path || `${pageName}.csv`;
  let preparedHeaders =
   uischemaData?.TableDownloadKeysName?.length > 0
    ? allowedFields.filter((e) =>
       uischemaData?.TableDownloadKeysName.includes(e.accessorKey)
      )
    : allowedFields;
  const preparedData = data.map((row, rowIndex) => {
   return updateDataHandler(preparedHeaders, row.original);
  });
  const csvData = arrayToCsv(
   preparedHeaders,
   preparedData,
   uischemaData.delimiter
  );
  download(csvData, filename, uischemaData.fileType || 'text/csv');
 };

 const SelectAllHandle = () => {
  let selectedData = [];
  if (selectActive) {
   setSelectActive(false);
   selectedData = data.map((e) => {
    return { ...e, [uischemaData.selectKey || 'isSelect']: false };
   });
  } else {
   setSelectActive(true);
   selectedData = data.map((e) => {
    return { ...e, [uischemaData.selectKey || 'isSelect']: true };
   });
  }
  setFormdata((pre) => {
   return { ...pre, [path]: selectedData };
  });
 };
 const materialIcons: Partial<MRT_Icons> = {
  SearchIcon: (props: any) => (
   <SearchIcon {...props} sx={{ color: 'inherit' }} />
  ),
  FilterListIcon: (props: any) => (
   <FilterList
    {...props}
    sx={{
     color: 'inherit',
     fontSize: 25,
     mx: 2,
    }}
   />
  ),
  FilterListOffIcon: () => (
   <FilterListOff
    sx={{
     color: 'inherit',
     fontSize: 25,
     mx: 2,
    }}
   />
  ),

  FullscreenIcon: () => <FullScreen />,
  FullscreenExitIcon: () => <ExitFullScreen  />,
  ViewColumnIcon: (props: any) => {
   return <ShowHideColumns />;
  },
  DensityLargeIcon: () => <ToggleDensity />,
  DensityMediumIcon: () => <ToggleDensity />,
  DensitySmallIcon: () => <ToggleDensity />,
  MoreHorizIcon: () => <ListIcon />,
 };
 const handleExpandedChange = async (next: any) => {
  const newState = typeof next === 'function' ? next(expanded) : next;
  const prevExpanded = expanded;

  const currentExpandedIds = Object.keys(newState).filter(
    (id) => newState[id] && !prevExpanded[id]
  );
  const idsNeedingData = currentExpandedIds.filter(
    (id) => !(renderTable?.getRow(id)?.subRows?.length > 0)
  );

  if (currentExpandedIds.length > 0) {
    if(idsNeedingData.length > 0) {
      updateTableData(idsNeedingData, true)
    }
  }
  setExpanded(newState);
 };
 const commonTableProperties = {
  id: path,
  key: path,
  columns: uischema.elements ? columns : [],
  data: useMemo(
          () => tableData?.filter((currentRow) => !currentRow[parentIdKey]),
          [tableData, parentIdKey]
        ),

  muiTableBodyRowProps: ({ row, table }) => {
   const tblDensity = table?.getState()?.density;
   return {
    onContextMenu: (event) => {
     event.preventDefault();
     setMenuAnchor(event.currentTarget);
     setCurrentRow(row);
    },
    sx: {
     backgroundColor:
    row.original?.[uischemaData.selectKey || 'isSelect'] === true
       ? `${theme.myTheme.palette.primary.light}21`
       : row.index % 2 === 0
       ? theme.myTheme.palette.common.white
       : 'transparent',
     border: `0.5px solid ${theme.myTheme.palette.grey[400]}80`,
     ' td': {
      borderBottom: 'none',
      padding:
       tblDensity === 'compact'
        ? '10px'
        : tblDensity === 'comfortable'
        ? '14px'
        : '18px',
     },
      ...uischema?.config?.style?.tableBodyRowProps
    },
   };
  },
  icons: materialIcons,
  enableColumnActions: false,
  enableSorting: uischemaData?.disableSorting ? false : true,
  enablePagination: uischemaData?.disablePagination ? false : true,
  enableRowActions: uischema.config?.action?.length > 0 ? true : false,
  enableKeyboardShortcuts: uischemaData?.enableKeyboardShortcuts || false,
  renderRowActionMenuItems: ({ row, table }) => {
   const menuItemArray = uischema.config?.action?.map(
    (uischemaAction, index) => {
     const scopeArray: string[] = uischemaAction.scope?.split('/');
     const childPath = composePaths(path, `${row.index}`);
     const widget = _.cloneDeep(uischemaAction);
     widget.config.style = {
      backgroundColor: 'transparent',
      color: theme.myTheme.palette.text.primary,
      fontSize: theme.myTheme.typography.fontSize,
      fontWeight: 'normal',
      boxShadow: 'none',
      justifyContent: 'start',
      padding: '5px 9px 5px 13px',
      whiteSpace: 'nowrap',
      '&:hover': {
       backgroundColor: theme.myTheme.palette.primary.main,
       color: theme.myTheme.palette.primary.contrastText,
       boxShadow: 'none',
      },
      ...widget.config.style,
     };
     widget.config.main.additionalData = {
      ...widget?.config?.main?.additionalData,
      disabled:
       widget?.config?.main?.disabled ||
       getComponentProps(
        `${pageName}:${fieldName}`,
        permissions,
        schema,
        rootSchema
       ).disabled,
      tableButtonPath: uischemaAction.accessorKey,
      rowData: row?.original,
      id: row.id,
     };
     return (
      <MenuItem
       key={childPath}
       sx={{
        padding: 0,
        minWidth: '130px',
        width: 'auto',
        '& .MuiButton-icon': {
         fill: theme.myTheme.palette.primary.main,
         color: theme.myTheme.palette.primary.main,
        },
        '&:hover': {
         backgroundColor: '#1BA1A6',
         color: '#ffffff',
         '& .MuiButton-icon': {
          fill: '#ffffff',
          color: '#ffffff',
         },
        },
       }}
      >
       <JsonFormsDispatch
        schema={schema}
        uischema={{ ...widget }}
        path={childPath}
        renderers={renderers}
       />
      </MenuItem>
     );
    }
   );
   return menuItemArray;
  },
  initialState: {
   showGlobalFilter: true,
   expanded: uischemaData?.initialState || false,
   showColumnFilters: false,
   density: uischemaData?.initialDensity || 'comfortable',
   columnVisibility: uischemaData?.initialColumnVisibility || {},
  },
  localization: {
   sortByColumnAsc: 'Sort by {column} Ascending',
   sortByColumnDesc: 'Sort by {column} Descending',
   sortedByColumnAsc: 'Sorted by {column} Ascending',
   sortedByColumnDesc: 'Sorted by {column} Descending'
  },
  enableColumnFilterModes: true,
  layoutMode: 'grid',
  positionGlobalFilter: 'left' as 'left',
  enableColumnResizing: uischemaData?.disableColumnResizing ? false : true,
  state: uischemaData.lazyLoading
   ? {
      isLoading: tableLoading,
      pagination,
      columnFilters,
      globalFilter,
      showProgressBars: isRefetching,
      sorting,
      expanded,
      columnFilterFns: columnFilterModes,
     }
   : { isLoading: tableLoading, expanded },
  enableRowOrdering: uischemaData?.enableDrag ? true : false,
  muiRowDragHandleProps: ({ table }) => ({
   onDragEnd: () => {
    const { draggingRow, hoveredRow } = table.getState();
    const draggableTableData = _.cloneDeep(tableData);
    if (hoveredRow && draggingRow) {
     draggableTableData.splice(
      hoveredRow.id,
      0,
      draggableTableData.splice(draggingRow.index, 1)[0]
     );
     setTableData(draggableTableData);
     !uischemaData.lazyLoading && handleChange(path, draggableTableData);
    }
   },
  }),
  enableGlobalFilter: uischemaData?.disableGlobalSearch ? false : true,
  enableStickyFooter: true,
  enableStickyHeader: true,
  displayColumnDefOptions: {
   'mrt-row-actions': {
    size: 150,
    muiTableHeadCellProps: ({ column }) => {
     return {
      sx: {
       '& .Mui-TableHeadCell-Content-Labels': {
        width: column.columns.length > 0 ? 'auto' : '100%',
        display: 'flex',
        justifyContent: 'space-between',
       },
       fontWeight: 'normal',
       backgroundColor: theme.myTheme.palette.primary.main,
       color: theme.myTheme.palette.common.white,
       height: '100%',
       borderBottom: 'none',
       ...uischema?.config?.style?.tableHeadstyle,
       '&:not(:last-of-type)': {
        position: 'relative',
        '&::after': {
         content: '""',
         position: 'absolute',
         top: '20%',
         right: 0,
         height: '60%',
         width: '2.5px',
         backgroundColor: '#e0e0e04d',
         display: 'block',
        },
       },
       '&:first-of-type': {
        paddingLeft: theme.myTheme.spacing(4),
       },
        ...uischema?.config?.style?.tableHeadstyle,
      },
     };
    },

    muiTableBodyCellProps: ({ cell, column }) => {
     return {
      align: 'center',
      sx: {
       borderRight: '1px solid #c6c6c6',
       '& .MuiButtonBase-root': {
        margin: 0,
        fill: theme.myTheme.palette.primary.main,
        opacity: 1,
        '--IconButton-hoverBg': 'none',
        '&:hover': {
         fill: theme.myTheme.palette.primary.dark,
        },
       },
      },
     };
    },
   },
   'mrt-row-drag': {
    header: '',
    size: 20,
    muiTableHeadCellProps: ({ column }) => {
     return {
      sx: {
       '& .Mui-TableHeadCell-Content-Labels': {
        width: column.columns.length > 0 ? 'auto' : '100%',
        display: 'flex',
        justifyContent: 'space-between',
        '& .MuiTableSortLabel-root': {
         opacity: 1,
         '& .MuiTableSortLabel-icon': {
          color: `${theme?.myTheme?.palette?.common?.white} !important`,
         },
        },
       },
       '& .MuiButtonBase-root:not(.Mui-disabled)': {
        color: theme?.myTheme?.palette?.common?.white,
       },
       '& .MuiInputBase-root': {
        color: theme?.myTheme?.palette?.common?.white,
        '&::before': {
         borderBottom: `1px solid ${theme?.myTheme?.palette?.common?.white}`,
        },
       },
       '& .MuiInputBase-root:hover:not(.Mui-disabled, .Mui-error)': {
        '&::before': {
         borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
        },
       },
       '& .MuiFormHelperText-root': {
        color: theme?.myTheme?.palette?.common?.white,
       },
       fontWeight: 'normal',
       fontSize: '14px',
       backgroundColor: theme.myTheme.palette.primary.main,
       color: theme.myTheme.palette.common.white,
       // padding: theme.myTheme.spacing(1),
       height: 'fit-content',
       borderBottom: 'none',
       ...uischema?.config?.style?.tableHeadstyle,
       '&:not(:last-of-type)': {
        position: 'relative',
       },
       // "&:first-of-type": {
       //   paddingLeft: theme.myTheme.spacing(4),
       // },
      },
     };
    },
   },

   'mrt-row-expand': {
    header: '',
    size: 40 + 24 * maxDepth,
    muiTableHeadCellProps: ({ column }) => {
     return {
      sx: {
       '& .Mui-TableHeadCell-Content-Labels': {
        width: column.columns.length > 0 ? 'auto' : '100%',
        display: 'flex',
        justifyContent: 'space-between',
        '& .MuiTableSortLabel-root': {
         opacity: 1,
         '& .MuiTableSortLabel-icon': {
          color: `${theme?.myTheme?.palette?.common?.white} !important`,
         },
        },
       },
       '& .MuiButtonBase-root:not(.Mui-disabled)': {
        color: theme?.myTheme?.palette?.common?.white,
       },
       '& .MuiInputBase-root': {
        color: theme?.myTheme?.palette?.common?.white,
        '&::before': {
         borderBottom: `1px solid ${theme?.myTheme?.palette?.common?.white}`,
        },
       },
       '& .MuiInputBase-root:hover:not(.Mui-disabled, .Mui-error)': {
        '&::before': {
         borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
        },
       },
       '& .MuiFormHelperText-root': {
        color: theme?.myTheme?.palette?.common?.white,
       },
       fontWeight: 'normal',
       fontSize: '14px',
       backgroundColor: theme.myTheme.palette.primary.main,
       color: theme.myTheme.palette.common.white,
       // padding: theme.myTheme.spacing(1),
       height: 'fit-content',
       borderBottom: 'none',
       ...uischema?.config?.style?.tableHeadstyle,
       '&:not(:last-of-type)': {
        position: 'relative',
       },
       // "&:first-of-type": {
       //   paddingLeft: theme.myTheme.spacing(4),
       // },
      },
     };
    },
   },
  },
  defaultDisplayColumn: {
   minSize: uischemaData.defaultColumnSize || 50,
  },
  enableExpandAll: uischemaData?.lazyLoading ? false : uischemaData?.enableExpandAll || true,
  enableExpanding: uischemaData?.enableExpanding || false,
  enableRowVirtualization: uischemaData?.enableExpanding || false,
  filterFromLeafRows: uischemaData?.filterFromLeafRows || true,
  enableTopToolbar: uischemaData?.enableTopToolbar ?? true,
  enableBottomToolbar: uischemaData?.enableBottomToolbar ?? true,
  getSubRows: (originalRow) => tableData?.filter((currentRow) => originalRow[rowIdKey] && currentRow[parentIdKey] && currentRow[parentIdKey] === originalRow[rowIdKey] ),
  renderToolbarInternalActions: ({ table }) => {
   const customIcons = uischemaData?.headerIcons?.elements.map((e: any) => {
    if (e.widget) {
     const scopeArray: string[] = e.widget.scope?.split('/');
     const actualElemPath: string = scopeArray[scopeArray.length - 1];
     const widget = _.cloneDeep(e.widget);
     const iconLabel =
      e?.widget?.config?.main?.iconLabel || e?.widget?.config?.main?.name;
     if (widget?.config?.main) {
      widget.config.main.additionalData = {
       ...widget?.config?.main?.additionalData,
       tableButtonPath: actualElemPath,
      };
     }
     return (
      <>
       <Grid
        sx={{
         textAlign: 'center',
         padding: '8px 4px 4px',
         color: theme.myTheme.palette.common.black,
         fill: theme.myTheme.palette.common.black,
         display: 'flex',
         flexDirection: 'column',
         justifyContent: 'center',
         '&:hover': {
          color: theme.myTheme.palette.primary.main,
          fill: theme.myTheme.palette.primary.main,
         },
        }}
       >
        {/* <Tooltip title={iconLabel}> */}
        <JsonFormsDispatch
         schema={schema}
         uischema={{ ...widget }}
         path={actualElemPath}
         key={actualElemPath}
         renderers={renderers}
        />
        {/* </Tooltip> */}

        <ComponentWrapper
         {...getComponentProps(
          `${pageName}:${actualElemPath}`,
          permissions,
          rootSchema?.properties?.[actualElemPath],
          rootSchema
         )}
        >
         <Typography
          sx={{
           fontSize: '9px',
           color: 'inherit',
           textAlign: 'center',
          }}
         >
          {iconLabel}
         </Typography>
        </ComponentWrapper>
       </Grid>
       {/* <Divider
                orientation="vertical"
                variant="middle"
                flexItem
                sx={{ height: "30px", alignSelf: "center" }}
              /> */}
      </>
     );
    }
   });
   const selectAllRow = (
    <>
     {!uischemaData.disableAction && (
      <>
       {uischemaData.Selection && (
        <>
         <Grid
          sx={{
           textAlign: 'center',
           padding: '8px 4px 4px',
           color: theme.myTheme.palette.common.black,
           fill: theme.myTheme.palette.common.black,
           display: 'flex',
           flexDirection: 'column',
           justifyContent: 'center',
           '&:hover': {
            color: theme.myTheme.palette.primary.main,
            fill: theme.myTheme.palette.primary.main,
           },
          }}
         >
          {/* <Tooltip title="Select All Rows"> */}
          <IconButton
           disabled={table.getPrePaginationRowModel().rows.length === 0}
           disableRipple
           sx={{
            margin: 0,
            padding: 0,
            color: 'inherit',
            fill: 'inherit',
           }}
           onClick={() => SelectAllHandle()}
          >
           <SelectAll />
          </IconButton>
          {/* </Tooltip> */}
          <Typography
           sx={{
            fontSize: '9px',
            color: 'inherit',
            display: 'block',
           }}
          >
           Select All
          </Typography>
         </Grid>
         {/* <Divider
                    orientation="vertical"
                    variant="middle"
                    flexItem
                    sx={{ height: "30px", alignSelf: "center" }}
                  /> */}
        </>
       )}
      </>
     )}
    </>
   );
   const seachButton = (
    <>
     <div style={{ textAlign: 'center' }}>
      <Button
       sx={{
        color: theme.myTheme.palette.primary.main,
        fontSize: 25,
        mt: '3px',
        '&:hover': { color: theme.myTheme.palette.primary.dark },
        display: 'grid',
       }}
       onClick={() => {
        updateTableData();
       }}
      >
       <SearchIcon />
       <Typography
        sx={{
         fontSize: '0.65rem',
         color: theme.myTheme.palette.primary.main,
        }}
       >
        Search
       </Typography>
      </Button>
     </div>
     <Divider
      orientation='vertical'
      variant='middle'
      flexItem
      sx={{ height: '30px', alignSelf: 'center' }}
     />
    </>
   );
   return (
    <Box
     sx={{
      display: 'flex',
      width: '100%',
      '& svg': { mx: { xs: 0, sm: 2.5 } },
      flexWrap: 'wrap',
      backgroundColor: 'transparent',
      gap: { xs: 0, md: '4px' },
     }}
    >
     {/* {uischemaData?.lazyLoading &&
          !(
            uischemaData?.disableGlobalSearch &&
            uischemaData?.disableColumnFilter
          )
            ? seachButton
            : null} */}
     {customIcons}

     {!(uischemaData?.disableDownloadFile ?? false) && (
      <Grid
       sx={{
        textAlign: 'center',
        padding: '8px 4px 4px',
        color: theme.myTheme.palette.common.black,
        fill: theme.myTheme.palette.common.black,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        '&:hover': {
         color: theme.myTheme.palette.primary.main,
         fill: theme.myTheme.palette.primary.main,
        },
       }}
      >
       {/* <Tooltip title={"Download File"}> */}
       <IconButton
        disabled={table.getPrePaginationRowModel().rows.length === 0}
        // size="small"
        disableRipple
        sx={{
         color: 'inherit',
         fill: 'inherit',
        }}
        onClick={() => generateCSV(table.getPrePaginationRowModel().rows)}
       >
        <Download />
       </IconButton>
       {/* </Tooltip> */}
       <Typography
        sx={{
         fontSize: '9px',
         color: 'inherit',
         display: 'block',
        }}
       >
        Download
       </Typography>
      </Grid>
     )}
     {selectAllRow}
     {!(uischemaData?.disableColumnFilter ?? false) && (
      <>
       <Grid
        sx={{
         textAlign: 'center',
         padding: '8px 4px 4px',
         color: theme.myTheme.palette.common.black,
         fill: theme.myTheme.palette.common.black,
         display: 'flex',
         flexDirection: 'column',
         justifyContent: 'center',
         '&:hover': {
          color: theme.myTheme.palette.primary.main,
          fill: theme.myTheme.palette.primary.main,
         },
        }}
       >
        <IconButton
         disableRipple
         sx={{
          margin: 0,
          padding: 0,
          color: 'inherit',
          fill: 'inherit',
          '&:hover': {
           backgroundColor: 'transparent',
          },
         }}
        >
         {/* <Tooltip title={"Filter"}> */}
         <MRT_ToggleFiltersButton
          title=''
          disableRipple
          table={table}
          sx={{ marginBottom: '-9px', color: 'inherit' }}
         />
        </IconButton>
        {/* </Tooltip> */}
        <Typography
         sx={{
          fontSize: '9px',
          color: 'inherit',
          display: 'block',
         }}
        >
         Filter
        </Typography>
       </Grid>
       {/* <Divider
                orientation="vertical"
                variant="middle"
                flexItem
                sx={{ height: "30px", alignSelf: "center" }}
              /> */}
      </>
     )}
     {!(uischemaData?.disableEditColumn ?? false) && (
      <>
       <Grid
        sx={{
         textAlign: 'center',
         padding: '8px 4px 4px',
         color: theme.myTheme.palette.common.black,
         fill: theme.myTheme.palette.common.black,
         display: 'flex',
         flexDirection: 'column',
         justifyContent: 'center',
         '&:hover': {
          color: theme.myTheme.palette.primary.main,
          fill: theme.myTheme.palette.primary.main,
         },
        }}
       >
        {/* <Tooltip title={"Edit Column"}> */}
        <IconButton
         disableRipple
         sx={{
          margin: 0,
          padding: 0,
          color: 'inherit',
          fill: 'inherit',
          '&:hover': {
           backgroundColor: 'transparent',
          },
         }}
        >
         <ShowHideColumnsMenu table={table} />
        </IconButton>
        {/* </Tooltip> */}
        <Typography
         sx={{
          fontSize: '9px',
          color: 'inherit',
          display: 'block',
         }}
        >
         Show/Hide Columns
        </Typography>
       </Grid>

       {/* <Divider
                orientation="vertical"
                variant="middle"
                flexItem
                sx={{ height: "30px", alignSelf: "center" }}
              /> */}
      </>
     )}

     {!(uischemaData?.disableFullScreenToggle ?? false) && (
      <>
       <Grid
        sx={{
         textAlign: 'center',
         padding: '8px 4px 4px',
         color: theme.myTheme.palette.common.black,
         fill: theme.myTheme.palette.common.black,
         display: 'flex',
         flexDirection: 'column',
         justifyContent: 'center',
         '&:hover': {
          color: theme.myTheme.palette.primary.main,
          fill: theme.myTheme.palette.primary.main,
         },
        }}
       >
        {/* <Tooltip title={isFullScreen ? "Exit" : "Full Screen"}> */}
        <IconButton
         disableRipple
         onClick={handleFullScreenToggle}
         sx={{
          margin: 0,
          padding: 0,
          color: 'inherit',
          fill: 'inherit',
          '&:hover': {
           backgroundColor: 'transparent',
          },
         }}
        >
         <MRT_ToggleFullScreenButton title='' table={table} />
        </IconButton>
        {/* </Tooltip> */}
        <Typography
         sx={{
          fontSize: '9px',
          color: 'inherit',
          display: 'block',
         }}
        >
         {isFullScreen ? 'Exit' : 'Full Screen'}
        </Typography>
       </Grid>
       {/* <Divider
                orientation="vertical"
                variant="middle"
                flexItem
                sx={{ height: "30px", alignSelf: "center" }}
              /> */}
      </>
     )}

     {!(uischemaData?.disableDensityToggle ?? false) && (
      <>
       <Grid
        sx={{
         textAlign: 'center',
         padding: '8px 4px 4px',
         color: theme.myTheme.palette.common.black,
         fill: theme.myTheme.palette.common.black,
         display: 'flex',
         flexDirection: 'column',
         justifyContent: 'center',
         '&:hover': {
          color: theme.myTheme.palette.primary.main,
          fill: theme.myTheme.palette.primary.main,
         },
        }}
       >
        {/* <Tooltip title={"Toggle Density"}> */}
        <IconButton
         disableRipple
         sx={{
          margin: 0,
          padding: 0,
          color: 'inherit',
          fill: 'inherit',
          '&:hover': {
           backgroundColor: 'transparent',
          },
         }}
        >
         <MRT_ToggleDensePaddingButton title='' table={table} />
        </IconButton>
        {/* </Tooltip> */}
        <Typography
         sx={{
          fontSize: '9px',
          color: 'inherit',
          display: 'block',
         }}
        >
         Toggle Density
        </Typography>
       </Grid>
       {/* <Divider
                orientation="vertical"
                variant="middle"
                flexItem
                sx={{ height: "30px", alignSelf: "center" }}
              /> */}
      </>
     )}
    </Box>
   );
  },
  muiTopToolbarProps: ({ column }) => ({
   sx: {
    // mb: isFullScreen ? "0px" : "16px",
    minHeight: 'unset',
    backgroundColor: '#f6f6f6',
    '& .MuiBox-root': {
     padding: 0,
    },
    '& > .MuiBox-root': {
     flexDirection: { xs: 'column', sm: 'row' },
     alignItems: 'flex-end'
    },
    '& > .MuiBox-root:not(.Mui-ToolbarDropZone)': {
     position: 'relative',
     paddingRight: '8px',
    },
    '& .MuiIconButton-root': {
     height: '25px',
     margin: 0,
     padding: 0,
     '& svg': {
      marginLeft: 0,
      marginRight: 0,
     },
    },
   },
  }),

  muiBottomToolbarProps: ({ column }) => ({
   sx: {
    backgroundColor: 'transparent',
    minHeight: '35px',
   },
  }),
  muiTableHeadProps: ({ table }) => ({
   sx: {
    fontWeight: 'normal',
    fontSize: '25px',
    '& .Mui-TableHeadCell-ResizeHandle-Wrapper': {
     marginRight: '-8px',
     zIndex: 10,
     '& .MuiDivider-root': {
      borderColor: 'transparent',
     },
     // display: "none",
    },
   },
  }),
  muiTableHeadRowProps: () => ({
   sx: {
    backgroundColor: theme.myTheme.palette.primary.main,
   },
  }),
  muiPaginationProps: () => ({
   showFirstButton: false,
   showLastButton: false,
   size: 'small',
   sx: {},
   rowsPerPageOptions: filteredPageSizeList,
  }),
  defaultColumn: {
   muiTableHeadCellProps: {
    sx: (uischema?.config.defaultStyle ||
     uischema?.config?.style?.tableHeadstyle) && {
     fontWeight: 'normal',
     fontSize: '14px',
     background: 'inherit',
     ...uischema?.config?.style?.tableHeadstyle,
    },
   },
   muiTableFooterCellProps: {
    sx: (uischema?.config.defaultStyle ||
     uischema?.config?.style?.tableFootertyle) && {
     fontWeight: 'normal',
     fontSize: '14px',
     ...uischema?.config?.style?.tableFootertyle,
    },
   },
  },

  muiTableBodyProps: {
   sx: {
    ...((uischema?.config.defaultStyle ||
     uischema?.config?.style?.tableBodystyle) && {
     ...uischema?.config?.style?.tableBodystyle,
    }),
   },
  },
  muiTableBodyCellProps: {
   sx: { ...uischema?.config?.style?.tableBodyCellProps },
  },
  muiSearchTextFieldProps: {
   placeholder: 'Search here',
   className: 'searchTextfield',
  },
  muiTableContainerProps: {
   sx: {
    overflowX: 'auto',
    overflowY: 'auto',
    scrollbarWidth: 'medium',
    '&::-webkit-scrollbar': {
     width: '0px',
     height: '6px',
    },
    '&::-webkit-scrollbar-thumb': {
     backgroundColor: 'darkgray',
     borderRadius: '6px',
    },
    '&::-webkit-scrollbar-track': {
     backgroundColor: 'transparent',
    },
    ...((uischema?.config.defaultStyle ||
     uischema?.config?.style?.tableContainerstyle) && {
     ...uischema?.config?.style?.tableContainerstyle,
    }),
   },
  },
  muiTablePaperProps: {
   elevation: 0,
   sx: {
    borderRadius: '0',
    backgroundColor: '#f6f6f6',
    borderBottom: `1px solid ${theme.myTheme.palette.grey[400]}`,
    ...(uischema?.config.defaultStyle ||
    uischema?.config?.style?.tablePaperstyle
     ? {
        borderRadius: '0',
        border: `1px solid ${theme.myTheme.palette.secondary.light}`,
        backgroundColor: '#f6f6f6',
        ...uischema?.config?.style?.tablePaperstyle,
       }
     : {}),
   },
  },
  renderEmptyRowsFallback: ({ table }) => {
   return (
    <Typography
     sx={{
      color: 'text.secondary',
      fontStyle: 'italic',
      maxWidth: {
          xs: 'min(100vw, 100%)',
          lg: 'min(calc(100vw - 220px), 100%)'
      },
      py: '2rem',
      textAlign: 'center',
      width: '100%',
     }}
    >
     {globalFilter || columnFilters.length
      ? 'No results found'
      : 'No records to display'}
    </Typography>
   );
  },
  getRowId: (row) => row[rowIdKey],
  onExpandedChange: uischemaData.lazyLoading ? handleExpandedChange : setExpanded,
  ...(uischemaData?.lazyLoading
   ? {}
   : { paginateExpandedRows: uischemaData?.paginateExpandedRows || false }),
 };
 const lazyLoadTable = {
  ...commonTableProperties,
  onColumnFiltersChange: setColumnFilters,
  onPaginationChange: setPagination,
  onGlobalFilterChange: setGlobalFilter,
  onSortingChange: setSorting,
  getRowCanExpand: (row) => !!row.original[rowIdKey],
  onColumnFilterFnsChange: setColumnFilterModes,
  manualPagination: true,
  manualSorting: true,
  manualFiltering: true,
  rowCount: rowCount,
 };
 const renderTable = useMaterialReactTable(
  //@ts-ignore
  uischemaData.lazyLoading ? lazyLoadTable : commonTableProperties
 );

 return (
  <Box
   component={'div'}
   key={`${path}-tableWrapper`}
   sx={{
    width: '100%',
    overflowX: 'auto',
    ...theme.DataGridStyle,
    ...componentStyle,
    borderRadius: 0,
    ...uischema?.config?.style,
   }}
  >
   <ThemeProvider key={path + 'theme'} theme={tableTheme}>
    <ComponentWrapper
     {...getComponentProps(
      `${pageName}:${fieldName}`,
      permissions,
      schema,
      rootSchema
     )}
    >
     <MaterialReactTable key={path} table={renderTable} />
     {uischemaData.enableRowMovement && (
      <Menu
       anchorEl={menuAnchor}
       open={Boolean(menuAnchor)}
       onClose={() => {
        setMenuAnchor(null);
        setCurrentRow(null);
       }}
      >
       <MenuItem
        onClick={() => {
         setSelectRow(currentRow);
         setMenuAnchor(null);
        }}
       >
        <IconButton>
         <ContentCopyIcon />
        </IconButton>
        Move
       </MenuItem>
       <MenuItem
        onClick={(e) => {
         handleMove('up', e);
         setMenuAnchor(null);
        }}
        disabled={!selectRow}
       >
        <IconButton>
         <ArrowUpward />
        </IconButton>
        Move Up
       </MenuItem>
       <MenuItem
        onClick={(e) => {
         handleMove('down', e);
         setMenuAnchor(null);
        }}
        disabled={!selectRow}
       >
        <IconButton>
         <ArrowDownward />
        </IconButton>
        Move Down
       </MenuItem>
       <MenuItem
        onClick={(e) => {
         handleMove('subRow', e);
         setMenuAnchor(null);
        }}
        disabled={!selectRow}
       >
        <IconButton>
         <ContentPasteIcon />
        </IconButton>
        Paste
       </MenuItem>
      </Menu>
     )}
    </ComponentWrapper>
   </ThemeProvider>
  </Box>
 );
});

export default memo(withJsonFormsControlProps(Table));

function convertColumn(columnParam: any) {
 const {
  UISchemacolumn,
  theme,
  serviceProvider,
  path,
  pageName,
  fieldName,
  schema,
  uischema,
  rootSchema,
  permissions,
  renderers,
  ctx,
  locale,
  timeZone,
  dateFormat,
  dateTimeFormat,
  serverDateTimeFormat,
  index,
  updateTableData,
  setColumnKeys,
  setColumnFilterModes,
  columnFilterModes,
  idToIndexMap,
  rowIdKey
 } = columnParam;
 const commonProperties = {
  size: UISchemacolumn.size,

  enableColumnFilter: UISchemacolumn.enableColumnFilter ?? true ? true : false,
  enableSorting:
   UISchemacolumn.enableSorting ?? UISchemacolumn.type !== 'action'
    ? true
    : false,
  columnFilterModeOptions: UISchemacolumn.columnFilterModeOptions || ['equals'],
  filterFn: getDefaultOperator(UISchemacolumn?.columnFilterModeOptions),
  muiFilterTextFieldProps: {
   onKeyDown: (e) => {
    if (e.key === 'Enter') {
     updateTableData();
    }
   },
  },
  muiTableHeadCellProps: ({ column, table }) => {
   const tblDensity = table?.getState()?.density;
   return {
    align:
     column.columns.length > 0
      ? 'center'
      : theme?.myTheme?.table?.header?.alignment?.[UISchemacolumn?.type] ||
        'left',
    sx: {
     '& .Mui-TableHeadCell-Content-Labels': {
      width: column.columns.length > 0 ? 'auto' : '100%',
      display: 'flex',
      justifyContent: 'space-between',
      '& .MuiTableSortLabel-root': {
       opacity: 1,
       '& .MuiTableSortLabel-icon': {
        color: `${theme?.myTheme?.palette?.common?.white} !important`,
       },
      },
     },
     '& .MuiButtonBase-root:not(.Mui-disabled)': {
      color: theme?.myTheme?.palette?.common?.white,
     },
     '& .MuiInputBase-root': {
      color: theme?.myTheme?.palette?.common?.white,
      '&::before': {
       borderBottom: `1px solid ${theme?.myTheme?.palette?.common?.white}`,
      },
     },
     '& .MuiInputBase-root:hover:not(.Mui-disabled, .Mui-error)': {
      '&::before': {
       borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
      },
      '&::after': {
       borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
       transform: 'scaleX(0)',
      },
     },
     '& .MuiInputBase-root.Mui-focused': {
      '&::before': {
       borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
      },
      '&::after': {
       borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
       transform: 'scaleX(0)',
      },
     },
     '& .MuiFormHelperText-root': {
      color: theme?.myTheme?.palette?.common?.white,
     },
     fontWeight: 'normal',
     fontSize: '14px',
     backgroundColor: theme.myTheme.palette.primary.main,
     color: theme.myTheme.palette.common.white,
     padding:
      tblDensity === 'compact'
       ? '6px'
       : tblDensity === 'comfortable'
       ? '10px'
       : '14px',
     paddingTop:
      tblDensity === 'compact'
       ? '6px'
       : tblDensity === 'comfortable'
       ? '10px'
       : '14px',
     paddingBottom:
      tblDensity === 'compact'
       ? '6px'
       : tblDensity === 'comfortable'
       ? '10px'
       : '14px',
     height: '100%',
     borderBottom: 'none',
     ...uischema?.config?.style?.tableHeadstyle,
     '&:not(:last-of-type)': {
      position: 'relative',
      '&::after': {
       content: '""',
       position: 'absolute',
       top: '20%',
       right: 0,
       height: '60%',
       width: '2.5px',
       backgroundColor: '#e0e0e04d',
       display: column.id === 'mrt-row-drag' ? 'none' : 'block',
      },
     },
     '&:first-of-type': {
      paddingLeft:
       column.columns.length > 0
        ? 0
        : column.id === 'mrt-row-drag'
        ? 0
        : theme.myTheme.spacing(4),

      '& .Mui-TableHeadCell-Content-Labels': {
       width: column.columns.length > 0 ? 'auto' : '100%',
       display: 'flex',
       justifyContent: 'space-between',
       '& .MuiTableSortLabel-root': {
        opacity: 1,
        '& .MuiTableSortLabel-icon': {
         color: `${theme?.myTheme?.palette?.common?.white} !important`,
        },
       },
      },
      '& .MuiButtonBase-root:not(.Mui-disabled)': {
       color: theme?.myTheme?.palette?.common?.white,
      },
      '& .MuiInputBase-root': {
       color: theme?.myTheme?.palette?.common?.white,
       '&::before': {
        borderBottom: `1px solid ${theme?.myTheme?.palette?.common?.white}`,
       },
      },
      '& .MuiInputBase-root:hover:not(.Mui-disabled, .Mui-error)': {
       '&::before': {
        borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
       },
       '&::after': {
        borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
        transform: 'scaleX(0)',
       },
      },
      '& .MuiInputBase-root.Mui-focused': {
       '&::before': {
        borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
       },
       '&::after': {
        borderBottom: `2px solid ${theme?.myTheme?.palette?.common?.white}`,
        transform: 'scaleX(0)',
       },
      },
      '& .MuiFormHelperText-root': {
       color: theme?.myTheme?.palette?.common?.white,
      },
     },
     '& .MuiCollapse-root': {
      paddingLeft: '2px',
     },
    },
   };
  },
  muiTableBodyCellProps: ({ cell, column }) => {
   return {
    align:
     theme?.myTheme?.table?.columns?.alignment?.[UISchemacolumn?.type] ||
     'left',
    sx: {
     borderRight: '1px solid #c6c6c6',
     '&:first-of-type': {
      paddingLeft: column.id === 'mrt-row-drag' ? 0 : theme.myTheme.spacing(4),
     },
    },
   };
  },
  Cell: ({ cell, column, row }) => {
   let updatedValue = toLocaleString(
    cell.getValue(),
    UISchemacolumn.type,
    UISchemacolumn?.dateFormat ?? serverDateTimeFormat,
    locale,
    timeZone,
    dateTimeFormat,
    dateFormat
   );
   const dynamicOutput = serviceProvider(
    ctx,
    {
     onClick: uischema.config.main.onCellRenderer || 'onCellRenderer',
    },
    {
     event: { _reactName: 'onClick' },
     path,
     paramValue: {
      cellkey: cell?.id?.substr(2),
      cellValue: cell.getValue(),
      rowValue: cell.row.original,
     },
    }
   );
   if (UISchemacolumn.widget) {
    const childPath = composePaths(path, `${idToIndexMap?.get(row.original?.[rowIdKey]) ?? row.index}`);
    const widget = _.cloneDeep(UISchemacolumn.widget);
    widget.config.style = {
     ...widget.config?.style,
     paddingTop: '0px',
     paddingBottom: '0px',
    };
    if (widget?.config?.main) {
     widget.config.main.additionalData = {
      ...widget?.config?.main?.additionalData,
      disabled:
       widget?.config?.main?.disabled ||
       getComponentProps(
        `${pageName}:${fieldName}`,
        permissions,
        schema,
        rootSchema
       ).disabled,
      tableButtonPath: UISchemacolumn.accessorKey,
      rowData: cell?.row?.original,
      id: cell.id,
     };
    }
    return (
     <Box
      component={'div'}
      key={`${cell.id}-cellWrapper`}
      sx={{
       justifyContent: 'space-around',
       display: 'flex',
       ...dynamicOutput?.cellStyle,
      }}
     >
      <JsonFormsDispatch
       schema={schema}
       uischema={{ ...widget }}
       path={childPath}
       key={cell.id}
       renderers={renderers}
      />
     </Box>
    );
   }
   if (uischema.config.main?.isLeaderBoard && index === 0) {
    return (
     <div
      style={{
       display: 'flex',
       flexDirection: 'row',
       justifyContent: 'space-between',
       alignItems: 'center',
      }}
     >
      <div
       style={{
        display: 'inline-block',
        overflow: 'auto',
        scrollbarWidth: 'none',
        fontSize: '12px',
        width: '35px',
        ...dynamicOutput?.cellStyle,
       }}
      >
       #{updatedValue}
      </div>
      <div style={{ display: 'flex', alignItems: 'center' }}>
       <LeaderboardAvatar width={40} />
      </div>
     </div>
    );
   }
   return (
    <div
     style={{
      display: 'inline-block',
      overflow: 'auto',
      scrollbarWidth: 'none',
      fontFamily: 'Poppins',
      fontSize: '12px',
      ...dynamicOutput?.cellStyle,
     }}
    >
     {updatedValue}
    </div>
   );
  },
 };
 const columnHelper = createMRTColumnHelper();
 if (
  Array.isArray(UISchemacolumn?.elements) &&
  UISchemacolumn.elements.length > 0
 ) {
  return columnHelper.group({
   ...commonProperties,
   header: UISchemacolumn.header,
   columns: UISchemacolumn.elements.map((e: any, index) => {
    setColumnFilterModes((prev) => {
     return {
      ...prev,
      [e.accessorKey]:
       columnFilterModes[e.accessorKey] ||
       getDefaultOperator(UISchemacolumn?.columnFilterModeOptions),
     };
    });
    if (e.columnKey) {
     setColumnKeys((pre) => ({
      ...pre,
      [e.accessorKey]: e.columnKey,
     }));
    }
    return convertColumn({ ...columnParam, UISchemacolumn: e, index });
   }),
  });
 } else {
  return columnHelper.accessor(UISchemacolumn.accessorKey, {
   ...commonProperties,
   id: UISchemacolumn.accessorKey,
   header: UISchemacolumn.header,
  });
 }
}

export function tableStyle(theme): any {
 return {
  palette: {
   mode: theme.myTheme.palette.mode,
   primary: {
    main: theme.myTheme.palette.primary.main,
    light: theme.myTheme.palette.primary.light,
    dark: theme.myTheme.palette.primary.dark,
   },
   secondary: {
    main: theme.myTheme.palette.secondary.main,
    light: theme.myTheme.palette.secondary.light,
    dark: theme.myTheme.palette.secondary.dark,
   },
   info: {
    main: theme.myTheme.palette.info.main,
    light: theme.myTheme.palette.info.light,
    dark: theme.myTheme.palette.info.dark,
   },
   background: {
    default: theme.myTheme.palette.background.paper,
   },
  },
 };
}
function getDefaultOperator(columnFilterModeOptions: string[]) {
 if (!columnFilterModeOptions) {
  return 'equals';
 }
 const isEqualAvailable = columnFilterModeOptions.find((e) => e === 'equals');
 if (isEqualAvailable) {
  return 'equals';
 }
 return columnFilterModeOptions[0];
}
