import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/model/service_project/service_projects_list_model.dart';

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

  /// Computed filtered project list
  List<ProjectItem> get filteredProjects {
    final query = searchQuery.value.trim().toLowerCase();
    if (query.isEmpty) return projects;

    return projects.where((p) {
      final nameMatch = p.name.toLowerCase().contains(query);
      final shortNameMatch = p.shortName.toLowerCase().contains(query);
      final addressMatch = p.address.toLowerCase().contains(query);
      final contactMatch = p.contactName.toLowerCase().contains(query);
      final clientMatch = p.client != null &&
          (p.client!.name.toLowerCase().contains(query) ||
              p.client!.contactPerson.toLowerCase().contains(query));

      return nameMatch ||
          shortNameMatch ||
          addressMatch ||
          contactMatch ||
          clientMatch;
    }).toList();
  }

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

      final result = await ApiService.getServiceProjectsListApi(
        pageNumber: pageNumber,
        pageSize: pageSize,
      );

      if (result != null && result.data != null) {
        projects.assignAll(result.data!.data);
      } else {
        projects.clear();
      }
    } catch (e) {
      // Optional: log or show error
      rethrow;
    } finally {
      isLoading.value = false;
    }
  }

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