import { CollectionState, Translate } from '@wix/bex-core';
import React from 'react';
import { Text } from '@wix/design-system';

export type MultipleSelection = boolean | number;

export type ReplaceMultiple<T> = Omit<T, 'multiple'> & T extends {
  multiple?: any;
}
  ? { multiple?: MultipleSelection }
  : {
      multiple: MultipleSelection;
    };

export function fromMultipleSelectionToBoolean(
  multipleSelection?: MultipleSelection,
): boolean {
  if (multipleSelection === undefined) {
    return false;
  }
  if (typeof multipleSelection === 'boolean') {
    return multipleSelection;
  }
  return multipleSelection > 1;
}

function maxSelectedItemsFromMultipleSelection(
  multipleSelection?: MultipleSelection,
): number {
  if (typeof multipleSelection === 'undefined') {
    return 1;
  }

  if (typeof multipleSelection === 'boolean') {
    return multipleSelection ? Infinity : 1;
  }

  return multipleSelection;
}

export function showMaxSelectionLabel(multipleSelection?: MultipleSelection) {
  const maxSelectedItems =
    maxSelectedItemsFromMultipleSelection(multipleSelection);
  return !(maxSelectedItems === 1 || maxSelectedItems === Infinity);
}

export type MaxSelectionLabelProps = {
  dataHook?: string;
  multiple?: MultipleSelection;
  t: Translate;
  customLabel?(_: { num: number; max: number }): string;
  selectedCount: number;
};

export function BulkSelectionMaxSelectionLabel(props: MaxSelectionLabelProps) {
  const { selectedCount, t, multiple, dataHook } = props;

  const maxSelectedItems = maxSelectedItemsFromMultipleSelection(multiple);

  let text;

  if (props.customLabel) {
    text = props.customLabel({
      num: selectedCount,
      max: maxSelectedItems,
    });
  } else if (selectedCount === 0) {
    text = t('cairo.bulkSelected.selectUpTo', {
      max: maxSelectedItems,
    });
  } else if (maxSelectedItems > selectedCount) {
    text = t('cairo.picker.itemsSelected', {
      total: selectedCount,
      max: maxSelectedItems,
    });
  } else {
    text = t('cairo.bulkSelected.withMaxNumber', {
      num: selectedCount,
      max: maxSelectedItems,
    });
  }

  return (
    <Text dataHook={dataHook} secondary>
      {text}
    </Text>
  );
}

export function reachedMaxSelection({
  collection,
  multiple,
}: {
  multiple?: MultipleSelection;
  collection: Pick<CollectionState<any, any>, 'bulkSelect'>;
}) {
  if (
    typeof multiple === 'undefined' ||
    typeof multiple === 'boolean' ||
    multiple <= 1
  ) {
    return false;
  }

  return collection.bulkSelect.selectedCount >= multiple;
}
