import { TableColumn } from '../model';
import { useCallback } from 'react';

export interface UseCreateWSRColumnBaseParams {
  horizontalScroll?: boolean;
}

export function useCreateWSRColumnBase({
  horizontalScroll,
}: UseCreateWSRColumnBaseParams) {
  return useCallback(
    (
      column: Omit<TableColumn<unknown>, 'render' | 'style'>,
      index: number,
      length: number,
    ) => {
      const { id, title, width, sortable, infoTooltipProps } = column;
      const lastColumn = index === length - 1;

      const lastColumnStyleNoHorizontalScroll =
        width != null
          ? {
              flexBasis: width,
              flexGrow: 1,
            }
          : {
              flex: 1,
            };

      const lastColumnStyle = horizontalScroll
        ? {
            flexBasis: width ?? 0,
            flexShrink: 0,
            flexGrow: 1,
          }
        : lastColumnStyleNoHorizontalScroll;

      const columnStyle = width == null ? { flex: 1 } : undefined;

      const style = lastColumn ? lastColumnStyle : columnStyle;

      return {
        id,
        key: id ?? index,
        title,
        style,
        width: lastColumn && !horizontalScroll ? undefined : width,
        sortable: id && sortable ? true : undefined,
        infoTooltipProps: infoTooltipProps?.content
          ? infoTooltipProps
          : undefined,
      };
    },
    [horizontalScroll],
  );
}
