/// Provider: Search Query Provider
///
/// Manages the current search query state for product filtering.
/// Includes debounce functionality with 1-second delay and minimum 2 characters.
library;

import 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/core/services/analytics_service.dart';

part 'search_query_provider.g.dart';

/// Search Query Provider
///
/// Holds the current search query string for filtering products.
/// Default is empty string which shows all products.
///
/// Features:
/// - 1-second debounce delay
/// - Only triggers search with 2+ non-whitespace characters
/// - Auto-clears search when query is empty or too short
///
/// Usage:
/// ```dart
/// // Read the current value
/// final searchQuery = ref.watch(searchQueryProvider);
///
/// // Update the value (will debounce)
/// ref.read(searchQueryProvider.notifier).updateQuery('gạch men');
/// ```
@riverpod
class SearchQuery extends _$SearchQuery {
  Timer? _debounceTimer;

  @override
  String build() {
    // Cancel timer when provider is disposed
    ref.onDispose(() {
      _debounceTimer?.cancel();
    });

    return ''; // Default: no search filter
  }

  /// Update search query with debounce
  ///
  /// Only updates state after 1 second of no typing.
  /// Only triggers API call if query has 2+ non-whitespace characters.
  void updateQuery(String query) {
    // Cancel previous timer
    _debounceTimer?.cancel();

    // Trim whitespace from query
    final trimmedQuery = query.trim();

    // If query is empty or too short, clear search immediately
    if (trimmedQuery.isEmpty || trimmedQuery.length < 2) {
      state = '';
      return;
    }

    // Set up debounce timer (1 second)
    _debounceTimer = Timer(const Duration(seconds: 1), () {
      // Only update if query still meets requirements after delay
      if (trimmedQuery.length >= 2) {
        state = trimmedQuery;
        // Log search analytics event
        AnalyticsService.logSearch(searchTerm: trimmedQuery);
      }
    });
  }

  /// Clear search query immediately
  void clear() {
    _debounceTimer?.cancel();
    state = '';
  }
}
