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

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

class CategoryController extends GetxController {
  final state = CategoryState();
  final TextEditingController searchTxtCtrl = TextEditingController();

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

  Future<void> filterCategories(String newValue) async {
    state.hasSuffixIcon.value = newValue.length != 0;

    state.isLoading.value = true;

    final categories = CategoryApi.buildCategoryTree(newValue);
    state.categories.clear();
    state.categories.addAll(categories);

    state.isLoading.value = false;
  }

  void clearSearchText() {
    searchTxtCtrl.text = '';
    state.hasSuffixIcon.value = false;
    final categories = CategoryApi.categories;
    state.categories.clear();
    state.categories.addAll(categories);
  }

  Future<void> fetchCategories() async {
    state.isLoading.value = true;
    state.hasError.value = false;

    final Map<String, dynamic> params = {
      'locale': await getLocale(),
      'parent_id': 1,
      // 'page': 1,
      // 'limit': 20,
    };

    final categories = await CategoryApi.getDescendantCategories(params);

    if (categories.length == 0) {
      state.hasError.value = true;
      state.isLoading.value = false;
      return;
    }

    state.categories.addAll(categories);

    state.hasError.value = false;
    state.isLoading.value = false;
    update();
  }

  void navigateToProducts(CategoryModel model) {
    final args = {
      'type': 'category_id',
      'id': model.id,
      'name': model.name,
    };
    navigateToProductListScreen(args);
  }
}
