import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/model/infra_project/infra_project_list.dart';

class InfraProjectController extends GetxController {
  final projects = <ProjectData>[].obs;
  final isLoading = false.obs;
  final searchQuery = ''.obs;

  // Filtered list
  List<ProjectData> get filteredProjects {
    final q = searchQuery.value.trim().toLowerCase();
    if (q.isEmpty) return projects;

    return projects.where((p) {
      return (p.name?.toLowerCase().contains(q) ?? false) ||
          (p.shortName?.toLowerCase().contains(q) ?? false) ||
          (p.projectAddress?.toLowerCase().contains(q) ?? false) ||
          (p.contactPerson?.toLowerCase().contains(q) ?? false);
    }).toList();
  }

  // Fetch Projects
  Future<void> fetchProjects({int pageNumber = 1, int pageSize = 20}) async {
    try {
      isLoading.value = true;

      final response = await ApiService.getInfraProjectsList(
        pageNumber: pageNumber,
        pageSize: pageSize,
      );

      if (response != null && response.data != null) {
        projects.assignAll(response.data!.data ?? []);
      } else {
        projects.clear();
      }
    } catch (e) {
      rethrow;
    } finally {
      isLoading.value = false;
    }
  }

  void updateSearch(String query) {
    searchQuery.value = query;
  }
}
