import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';

/// Consolidated base logic controller that provides common functionality
/// for pages with search and filter capabilities.
///
/// This replaces the duplicate BaseLogic classes across different packages.
class BasePageLogic extends GetxController {
  final RxBool isFilterSelected = false.obs;
  final RxBool isSearchSelected = false.obs;
  final RxnString searchValue = RxnString();
  final TextEditingController searchTextController = TextEditingController();

  // Debounce time configuration
  static const Duration _defaultDebounceTime = Duration(milliseconds: 600);

  /// Sets up search callback with debouncing
  /// [onSearchChanged] will be called when search value changes after debounce delay
  /// [debounceTime] custom debounce duration, defaults to 600ms
  void setSearchCallback(
    void Function(String?)? onSearchChanged, {
    Duration debounceTime = _defaultDebounceTime,
  }) {
    debounce<String?>(searchValue, (val) {
      if (val != null && val.trim().isNotEmpty) {
        onSearchChanged?.call(val);
      } else {
        // Call with null/empty to handle search clear
        onSearchChanged?.call(null);
      }
    }, time: debounceTime);
  }

  /// Toggles search visibility state
  void toggleSearch() {
    isSearchSelected.value = !isSearchSelected.value;

    // Clear search when hiding
    if (!isSearchSelected.value) {
      clearSearch();
    }
  }

  /// Clears search input and resets state
  void clearSearch() {
    if (searchTextController.text.isNotEmpty) {
      searchTextController.clear();
      searchValue.value = null;
    }
  }

  /// Toggles filter selection state
  void toggleFilter() {
    isFilterSelected.value = !isFilterSelected.value;
  }

  /// Resets all states to initial values
  void resetStates() {
    isFilterSelected.value = false;
    isSearchSelected.value = false;
    clearSearch();
  }

  @override
  void onInit() {
    super.onInit();

    // Bind search controller to reactive value
    searchTextController.addListener(() {
      searchValue.value = searchTextController.text;
    });
  }

  @override
  void onClose() {
    searchTextController.dispose();
    super.onClose();
  }
}

/// Backward compatibility alias - will be deprecated
@Deprecated('Use BasePageLogic instead. This will be removed in future versions.')
typedef BaseLogic = BasePageLogic;
