import { listItemSectionBuilder } from '@wix/design-system';
import { FiltersMap, CollectionState, ArrayField } from '@wix/bex-core';
import { ListItem, useBuildOption } from '.';
import { DropdownCollectionFilterState } from '../state';
import {
  KeyedItemOption,
  MultiSelectCheckboxFilterBaseOption,
} from '../components/MultiSelectCheckboxFilterBase';

interface UseCollectionOptionsProps<V, F extends FiltersMap> {
  collection: CollectionState<V, F>;
  dropdownCollectionFilterState: DropdownCollectionFilterState<V, F>;
  renderItem?: (item: V, index: number) => ListItem;
  filter: ArrayField<V>;
}

export function useCollectionOptions<V, F extends FiltersMap>({
  collection,
  dropdownCollectionFilterState,
  renderItem,
  filter,
}: UseCollectionOptionsProps<V, F>) {
  const buildOption = useBuildOption<V>({
    filter,
    renderItem,
    checkbox: true,
  });

  const {
    result: { keyedItems },
    query: {
      search: { isEmpty: isEmptySearch },
    },
  } = collection;

  // Original behavior: promote when not searching
  const shouldPromote = isEmptySearch;

  // Always use the snapshot from onOptionsShow to maintain consistent session behavior
  // This prevents items from jumping during the session, even if snapshot is empty
  const itemsToPromote = dropdownCollectionFilterState.promotedItems;

  const promotedItems = shouldPromote
    ? keyedItems.filter((item) => itemsToPromote.includes(item.key))
    : [];

  const finalOptions = promotedItems.length
    ? promotedItems.map(buildOption)
    : [];

  const divider =
    shouldPromote &&
    promotedItems.length &&
    promotedItems.length !== keyedItems.length
      ? [
          listItemSectionBuilder({
            id: 'promoted-section-divider',
            type: 'divider',
          }),
        ]
      : [];

  const promotedOptions: MultiSelectCheckboxFilterBaseOption<V>[] = [
    ...finalOptions,
    ...divider,
  ];

  const promotedItemKeys = new Set(itemsToPromote);

  const otherOptions: KeyedItemOption<V>[] = (
    shouldPromote
      ? keyedItems.filter(({ key }) => !promotedItemKeys.has(key))
      : keyedItems
  ).map(buildOption);

  const options = [...(shouldPromote ? promotedOptions : []), ...otherOptions];

  return {
    options,
  };
}
