import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../main.dart';
import '../../app.dart';
import 'state.dart';

class SSearchController extends GetxController {
  // Timer? _debounce;

  final SearchState state = SearchState();

  // final TextEditingController decoratedSearchTxtCtrl = TextEditingController();
  final TextEditingController searchTxtCtrl = TextEditingController();
  final FocusNode searchFocusNode = FocusNode();

  // final FocusNode decoratedSearchFocusNode = FocusNode();

  @override
  void onInit() {
    searchTxtCtrl.addListener(_listenSearchValue);

    super.onInit();
  }

  @override
  void dispose() {
    debugPrint('SearchController dispose');
    searchTxtCtrl.dispose();
    // decoratedSearchTxtCtrl.dispose();
    // decoratedSearchFocusNode.dispose();
    super.dispose();
  }

  // void _printLatestValue() {
  //   debugPrint('Text field: ${searchTxtCtrl.text}');
  // }

  // void _listenFocusNode() {
  //   searchFocusNode.addListener(() {
  //     debugPrint('Has Focus: ${searchFocusNode.hasFocus} ');

  //     if (searchFocusNode.hasFocus) {}
  //   });
  // }

  void _listenSearchValue() {
    if (searchTxtCtrl.text.length > 0) {
      state.hasSuffixIcon.value = true;
    } else {
      state.hasSuffixIcon.value = false;
    }
  }

  void onSearchChanged(String query) {
    debugPrint('onSearchChanged $query');
    if (query.length > 0) {
      state.hasSuffixIcon.value = true;
    } else {
      state.hasSuffixIcon.value = false;
    }
    // if (_debounce?.isActive ?? false) _debounce!.cancel();
    // _debounce = Timer(const Duration(milliseconds: 600), () {
    //   debugPrint('onSearchChanged $query');
    //   fetchSearchResult(query);
    // });
  }

  void goBack() {
    Get.back();
  }

  void onSearchIconPressed() {
    debugPrint('onSearchIconPressed');
  }

  void onDecoratedTxtFormFieldTap(String value) {
    debugPrint('onTxtFormFieldTap $value');

    if (value.isNotEmpty) {
      final args = {
        'type': 'search',
        'id': value.trim().toLowerCase(),
        'name': 'search_key'.tr + ': ' + value.trim(),
      };

      navigateToProductListScreen(args);
    } else {
      searchFocusNode.unfocus();
    }
  }

  void clearSearchText() {
    state.hasSuffixIcon.value = false;
    searchTxtCtrl.text = '';
  }

  void onProductTapped(ProductModel productModel) {
    debugPrint('onProductTapped');
  }

  Future<void> saveSearchHistory(String searchTxt) async {
    // Saving history in these 2 cases.
    // 1. on 'Done' button tapped.
    // 2. on 'Search Result' tapped.
    try {
      final keyTxt = searchTxt.trim();
      if (keyTxt.length > 0) dbHelper.save(SearchHistory(keyword: keyTxt));
    } catch (e) {
      debugPrint('error saveSearchHistory $e');
    }
  }

  Future<void> getSearchHistory() async {
    try {
      state.isLoading.value = true;
      state.searchHistoryList.clear();
      List<SearchHistory> list = await dbHelper.getSearchHistory();
      state.searchHistoryList.addAll(list);

      state.isLoading.value = false;
    } catch (e) {
      debugPrint('error saveSearchHistory $e');
      state.isLoading.value = false;
    }
  }

  Future<void> resetSearchHistory() async {
    try {
      await dbHelper.resetDb();
      state.searchHistoryList.clear();
    } catch (e) {
      debugPrint('error clearSearchHistory $e');
    }
  }

  Future<void> fetchSearchResult(String key) async {
    debugPrint('fetchSearchResult');
    state.isLoading.value = true;

    state.searchResult.clear();

    // final params = {
    //   'limit': 10,
    //   'page': 1,
    //   'locale': 'tr',
    //   'currency': 'tmt',
    //   'url_key': key,
    // };

    // final result = await SearchApi.getSearchResult(params);
    // if (result != null) {
    //   state.searchResult.addAll(result);
    // }
    state.isLoading.value = false;
  }
}
