import { useMemo } from 'react';
import { DropdownSelectState } from '../state';
import { Filter } from '@wix/bex-core';
import { useDropdownTranslationContext } from '../providers';

export interface UseDropdownPlaceholderParams<V> {
  dropdownSelect: DropdownSelectState<V>;
  filter: Filter<V[]>;
  shouldShowPlaceholder: boolean;
  isOverflow: boolean;
  placeholderProp?: string;
}

export function useDropdownPlaceholder<V>({
  dropdownSelect,
  filter,
  shouldShowPlaceholder,
  isOverflow,
  placeholderProp,
}: UseDropdownPlaceholderParams<V>) {
  const {
    select: { selectedValues },
    container,
  } = dropdownSelect;
  const { translate } = useDropdownTranslationContext();

  const selectedValuesText = useMemo(() => {
    return selectedValues.map(({ item }) => filter.itemName(item)).join(', ');
  }, [selectedValues]);

  return useMemo(() => {
    let placeholder = '';

    if (!shouldShowPlaceholder) {
      return { selectedValuesText, placeholder };
    }

    if (selectedValues.length !== 0) {
      if (
        (process.env.NODE_ENV === 'test' && selectedValuesText.length > 40) ||
        isOverflow
      ) {
        placeholder = translate('selectedItems', {
          total: selectedValues.length,
        });
      } else {
        placeholder = selectedValuesText;
      }
    } else if (placeholderProp) {
      placeholder = placeholderProp;
    } else {
      placeholder = translate('placeholder');
    }

    return { selectedValuesText, placeholder };
  }, [
    selectedValues,
    shouldShowPlaceholder,
    isOverflow,
    container.initTask.status.status,
  ]);
}
