import { TableColumn } from '../model';
import React, { useCallback, type ReactNode } from 'react';
import { Box, Text } from '@wix/design-system';
import { getFieldTypeIcon } from '../utils/fieldTypePrefixIcons';

export interface UseCreateWSRColumnBaseParams {
  horizontalScroll?: boolean;
  /** When true, renders field-type prefix icons in column headers. */
  showFieldTypeIcons?: boolean;
}

export function useCreateWSRColumnBase({
  horizontalScroll,
  showFieldTypeIcons,
}: UseCreateWSRColumnBaseParams) {
  return useCallback(
    (
      column: Omit<TableColumn<unknown>, 'render' | 'style'>,
      index: number,
      length: number,
    ) => {
      const { id, title, width, sortable, infoTooltipProps, fieldType } =
        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;
      const renderedTitle: ReactNode =
        title && showFieldTypeIcons ? (
          <Box gap="SP1" verticalAlign="middle" minWidth={0}>
            <Box flexShrink={0}>{getFieldTypeIcon({ fieldType })}</Box>
            {typeof title === 'string' ? (
              <Text size="small" ellipsis appendTo="window">
                {title}
              </Text>
            ) : (
              title
            )}
          </Box>
        ) : (
          title
        );

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