import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/model/service_project/job_allocation_model.dart';
import 'package:on_field_work/helpers/services/api_service.dart';

class ServiceProjectAllocationController extends GetxController {
  final projectId = ''.obs;

  // Roles
  var roles = <TeamRole>[].obs;      
  var selectedRole = Rxn<TeamRole>();

  // Employees
  var roleEmployees = <Employee>[].obs; 
  var selectedEmployees = <Employee>[].obs;
  final displayController = TextEditingController();

  // Loading
  var isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    ever(selectedEmployees, (_) {
      displayController.text = selectedEmployees.isEmpty
          ? ''
          : selectedEmployees
              .map((e) => '${e.firstName} ${e.lastName}')
              .join(', ');
    });
  }

  // Fetch all roles
  Future<void> fetchRoles() async {
    isLoading.value = true;
    final result = await ApiService.getTeamRoles(); 
    if (result != null) {
      roles.assignAll(result);
    }
    isLoading.value = false;
  }

  // Fetch employees by role
  Future<void> fetchEmployeesByRole(String roleId) async {
    isLoading.value = true;
    final allocations = await ApiService.getServiceProjectAllocationList(
        projectId: projectId.value);

    if (allocations != null) {
      roleEmployees.assignAll(
        allocations
            .where((a) => a.teamRole.id == roleId)
            .map((a) => a.employee)
            .toList(),
      );
    }
    isLoading.value = false;
  }

  void toggleEmployee(Employee emp) {
    if (selectedEmployees.contains(emp)) {
      selectedEmployees.remove(emp);
    } else {
      selectedEmployees.add(emp);
    }
  }

  Future<bool> submitAllocation() async {
    final payload = selectedEmployees
        .map((e) => {
              "projectId": projectId.value,
              "employeeId": e.id,
              "teamRoleId": selectedRole.value?.id,
              "isActive": true,
            })
        .toList();

    return await ApiService.manageServiceProjectAllocation(payload: payload);
  }
}
