import 'package:get/get.dart';
import 'package:marco/helpers/services/app_logger.dart';
import 'package:marco/helpers/services/api_service.dart';
import 'package:marco/controller/project_controller.dart';

class DashboardController extends GetxController {
  // Observables
  final RxList<Map<String, dynamic>> roleWiseData = <Map<String, dynamic>>[].obs;
  final RxBool isLoading = false.obs;
  final RxString selectedRange = '15D'.obs;
  final RxBool isChartView = true.obs;

  // Inject the ProjectController
  final ProjectController projectController = Get.find<ProjectController>();

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

    logSafe(
      'DashboardController initialized with project ID: ${projectController.selectedProjectId.value}',
      level: LogLevel.info,
       
    );

    if (projectController.selectedProjectId.value.isNotEmpty) {
      fetchRoleWiseAttendance();
    }

    // React to project change
    ever<String>(projectController.selectedProjectId, (id) {
      if (id.isNotEmpty) {
        logSafe('Project changed to $id, fetching attendance', level: LogLevel.info,  );
        fetchRoleWiseAttendance();
      }
    });

    // React to range change
    ever(selectedRange, (_) {
      fetchRoleWiseAttendance();
    });
  }

  int get rangeDays => _getDaysFromRange(selectedRange.value);

  int _getDaysFromRange(String range) {
    switch (range) {
      case '15D':
        return 15;
      case '30D':
        return 30;
      case '7D':
      default:
        return 7;
    }
  }

  void updateRange(String range) {
    selectedRange.value = range;
    logSafe('Selected range updated to $range', level: LogLevel.debug);
  }

  void toggleChartView(bool isChart) {
    isChartView.value = isChart;
    logSafe('Chart view toggled to: $isChart', level: LogLevel.debug);
  }

  Future<void> refreshDashboard() async {
    logSafe('Manual dashboard refresh triggered.', level: LogLevel.debug);
    await fetchRoleWiseAttendance();
  }

  Future<void> fetchRoleWiseAttendance() async {
    final String projectId = projectController.selectedProjectId.value;

    if (projectId.isEmpty) {
      logSafe('Project ID is empty, skipping API call.', level: LogLevel.warning);
      return;
    }

    try {
      isLoading.value = true;

      final List<dynamic>? response =
          await ApiService.getDashboardAttendanceOverview(projectId, rangeDays);

      if (response != null) {
        roleWiseData.value =
            response.map((e) => Map<String, dynamic>.from(e)).toList();
        logSafe('Attendance overview fetched successfully.', level: LogLevel.info);
      } else {
        roleWiseData.clear();
        logSafe('Failed to fetch attendance overview: response is null.', level: LogLevel.error);
      }
    } catch (e, st) {
      roleWiseData.clear();
      logSafe(
        'Error fetching attendance overview',
        level: LogLevel.error,
        error: e,
        stackTrace: st,
      );
    } finally {
      isLoading.value = false;
    }
  }
}
