/**
 * Copyright Aquera Inc 2025
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */

export class ComboboxSearchManager {
  private debounceTimer: ReturnType<typeof setTimeout> | null = null;

  filter(
    searchValue: string,
    originalItems: any[],
    getSearchText: (item: any) => string,
  ): { filteredItems: any[]; showNoResults: boolean } {
    if (!originalItems || originalItems.length === 0) {
      return { filteredItems: [], showNoResults: true };
    }

    if (!searchValue || searchValue.trim() === '') {
      return { filteredItems: [...originalItems], showNoResults: false };
    }

    const needle = searchValue.toLowerCase();
    const filteredItems = originalItems.filter((item: any) => {
      const text = getSearchText(item);
      return text.toLowerCase().includes(needle);
    });

    return { filteredItems, showNoResults: filteredItems.length === 0 };
  }

  debounceSearch(
    callback: (query: string) => void,
    query: string,
    debounceMs: number,
  ): void {
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
    this.debounceTimer = setTimeout(() => {
      callback(query);
      this.debounceTimer = null;
    }, debounceMs);
  }

  cancelDebounce(): void {
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
      this.debounceTimer = null;
    }
  }
}
