import { useMemo } from 'react';
import { useIsMobile } from './useIsMobile';
import { TableProps, TableColumn } from '@wix/design-system';
import { ColumnSizesState } from '../state/ColumnSizesState';

export function useCollectionTableResize({
  columns,
  horizontalScroll,
  userResizeProps,
  columnSizesState,
  isVirtualized,
}: {
  columns: TableColumn[];
  horizontalScroll: boolean | undefined;
  userResizeProps?: TableProps['resizeProps'];
  columnSizesState: ColumnSizesState | null;
  isVirtualized?: boolean;
}) {
  const experimentEnabled =
    columnSizesState?.isResizeExperimentEnabled ?? false;
  const isMobile = useIsMobile();

  const areAllColumnsPixelWidth = useMemo(
    () => columns.every((col) => col.width?.toString().match(/^\d+px$/)),
    [columns],
  );

  const isResizable =
    experimentEnabled &&
    !isMobile &&
    !isVirtualized &&
    !!horizontalScroll &&
    areAllColumnsPixelWidth;

  const resizePlaceholderColumn = useMemo(
    () => ({ title: '', width: '100%', render: () => null }),
    [],
  );

  const tableResizeProps: TableProps['resizeProps'] | undefined = isResizable
    ? {
        ...userResizeProps,
        minColumnWidth: userResizeProps?.minColumnWidth ?? 74,
        onColumnResizeEnd(columnId, endWidth, event) {
          columnSizesState?.updateColumnWidth(columnId, Number(endWidth));
          userResizeProps?.onColumnResizeEnd?.(columnId, endWidth, event);
        },
      }
    : undefined;

  return {
    isResizable,
    tableResizeProps,
    resizePlaceholderColumn,
  };
}
