import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/app_logger.dart'; 
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/model/global_project_model.dart';
import 'package:on_field_work/helpers/services/storage/local_storage.dart';

class ProjectController extends GetxController {
  RxList<GlobalProjectModel> projects = <GlobalProjectModel>[].obs;
  RxString selectedProjectId = ''.obs;
  RxBool isProjectListExpanded = false.obs;
  RxBool isProjectSelectionExpanded = false.obs;

  RxBool isProjectDropdownExpanded = false.obs;
  RxBool isLoading = true.obs;
  RxBool isLoadingProjects = true.obs;
  RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;

  GlobalProjectModel? get selectedProject {
    if (selectedProjectId.value.isEmpty) return null;
    return projects.firstWhereOrNull((p) => p.id == selectedProjectId.value);
  }

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

  void clearProjects() {
    projects.clear();
    selectedProjectId.value = '';

    isProjectSelectionExpanded.value = false;
    isProjectListExpanded.value = false;
    isProjectDropdownExpanded.value = false;
    isLoadingProjects.value = false;
    isLoading.value = false;
    uploadingStates.clear();

    LocalStorage.saveString('selectedProjectId', '');

    logSafe("Projects cleared and UI states reset.");
    update();
  }

  /// Fetches projects and initializes selected project.
  Future<void> fetchProjects() async {
    isLoadingProjects.value = true;
    isLoading.value = true;

    final response = await ApiService.getGlobalProjects();

    if (response != null && response.isNotEmpty) {
      projects.assignAll(
        response.map((json) => GlobalProjectModel.fromJson(json)).toList(),
      );

      String? savedId = LocalStorage.getString('selectedProjectId');
      if (savedId != null && projects.any((p) => p.id == savedId)) {
        selectedProjectId.value = savedId;
      } else {
        selectedProjectId.value = projects.first.id.toString();
        LocalStorage.saveString('selectedProjectId', selectedProjectId.value);
      }

      isProjectSelectionExpanded.value = false;
      logSafe("Projects fetched: ${projects.length}");
    } else {
      logSafe("No Global projects found or API call failed.", level: LogLevel.warning);
    }

    isLoadingProjects.value = false;
    isLoading.value = false;
    update(['dashboard_controller']);
  }

  Future<void> updateSelectedProject(String projectId) async {
    selectedProjectId.value = projectId;
    await LocalStorage.saveString('selectedProjectId', projectId);
    logSafe("Selected project updated to $projectId");
    update(['selected_project']);
  }
}
