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/helpers/widgets/my_form_validator.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/model/dailyTaskPlanning/master_work_category_model.dart';

class AddTaskController extends GetxController {
  RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;
  MyFormValidator basicValidator = MyFormValidator();
  RxnString selectedCategoryId = RxnString();
  RxnString selectedCategoryName = RxnString();
  var categoryIdNameMap = <String, String>{}.obs;

  List<Map<String, dynamic>> roles = [];
  RxnString selectedRoleId = RxnString();
  RxBool isLoadingWorkMasterCategories = false.obs;
  RxList<WorkCategoryModel> workMasterCategories = <WorkCategoryModel>[].obs;

  RxBool isLoading = false.obs;

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

  String? formFieldValidator(String? value, {required String fieldType}) {
    if (value == null || value.trim().isEmpty) {
      return 'This field is required';
    }
    if (fieldType == "target" && int.tryParse(value.trim()) == null) {
      return 'Please enter a valid number';
    }
    if (fieldType == "description" && value.trim().length < 5) {
      return 'Description must be at least 5 characters';
    }
    return null;
  }

  Future<bool> assignDailyTask({
    required String workItemId,
    required int plannedTask,
    required String description,
    required List<String> taskTeam,
    DateTime? assignmentDate,
  }) async {
    logSafe("Starting task assignment...", level: LogLevel.info);

    final response = await ApiService.assignDailyTask(
      workItemId: workItemId,
      plannedTask: plannedTask,
      description: description,
      taskTeam: taskTeam,
      assignmentDate: assignmentDate,
    );

    if (response == true) {
      logSafe("Task assigned successfully.", level: LogLevel.info);
      showAppSnackbar(
        title: "Success",
        message: "Task assigned successfully!",
        type: SnackbarType.success,
      );
      return true;
    } else {
      logSafe("Failed to assign task.", level: LogLevel.error);
      showAppSnackbar(
        title: "Error",
        message: "Failed to assign task.",
        type: SnackbarType.error,
      );
      return false;
    }
  }

  Future<bool> createTask({
    required String parentTaskId,
    required String workAreaId,
    required String activityId,
    required int plannedTask,
    required String comment,
    required String categoryId,
    DateTime? assignmentDate,
  }) async {
    logSafe("Creating new task...", level: LogLevel.info);

    final response = await ApiService.createTask(
      parentTaskId: parentTaskId,
      plannedTask: plannedTask,
      comment: comment,
      workAreaId: workAreaId,
      activityId: activityId,
      assignmentDate: assignmentDate,
      categoryId: categoryId,
    );

    if (response == true) {
      logSafe("Task created successfully.", level: LogLevel.info);
      showAppSnackbar(
        title: "Success",
        message: "Task created successfully!",
        type: SnackbarType.success,
      );
      return true;
    } else {
      logSafe("Failed to create task.", level: LogLevel.error);
      showAppSnackbar(
        title: "Error",
        message: "Failed to create task.",
        type: SnackbarType.error,
      );
      return false;
    }
  }

  Future<void> fetchWorkMasterCategories() async {
    isLoadingWorkMasterCategories.value = true;

    try {
      final response = await ApiService.getMasterWorkCategories();
      if (response != null) {
        final dataList = response['data'] ?? [];

        final parsedList = List<WorkCategoryModel>.from(
          dataList.map((e) => WorkCategoryModel.fromJson(e)),
        );

        workMasterCategories.assignAll(parsedList);
        final mapped = {for (var item in parsedList) item.id: item.name};
        categoryIdNameMap.assignAll(mapped);

        logSafe("Work categories fetched: ${dataList.length}", level: LogLevel.info);
      } else {
        logSafe("No work categories found or API call failed.", level: LogLevel.warning);
      }
    } catch (e, st) {
      logSafe("Error parsing work categories", level: LogLevel.error, error: e, stackTrace: st);
      workMasterCategories.clear();
      categoryIdNameMap.clear();
    }

    isLoadingWorkMasterCategories.value = false;
    update();
  }

  void selectCategory(String id) {
    selectedCategoryId.value = id;
    selectedCategoryName.value = categoryIdNameMap[id];
    logSafe("Category selected", level: LogLevel.debug,  );
  }
}
