import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dikantin/app/data/providers/menu_provider.dart';

import '../../../data/models/search_model.dart';

class vsmController extends GetxController {
  final menuProvider = MenuProvider().obs;
  final searchResults = <Datasearch>[].obs;
  final isLoading = false.obs; // Tambahkan isLoading
  final TextEditingController searchController = TextEditingController();
  Timer? debounce; //

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

  void setLoading(bool value) {
    isLoading.value = value; // Metode untuk mengatur status isLoading
  }

  Future<void> refreshData() async {
    await search('');
  }

  Future<void> search(String keyword) async {
    debounce
        ?.cancel(); // Pastikan debounce dibatalkan sebelum membuat yang baru

    debounce = Timer(Duration(milliseconds: 1500), () async {
      try {
        setLoading(true);
        final results = await menuProvider.value.vsmSearch(keyword);
        searchResults.assignAll(results.data ?? []);
      } catch (e) {
        print('Error during search: $e');
        searchResults.clear();
      } finally {
        setLoading(false);
      }
    });
  }

  void onClose() {
    debounce
        ?.cancel(); // Pastikan debounce dibatalkan saat controller dihancurkan
    searchController.dispose();
    super.onClose();
  }
}
