import 'dart:async';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:siro_admin/constant/links.dart';
import 'package:siro_admin/controller/functions/crud.dart';
import '../../print.dart';

class DashboardV2Controller extends GetxController {
  bool isLoading = true;
  Map<String, dynamic> realtimeData = {};
  List<dynamic> smartAlerts = [];
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    fetchRealtimeData();
    fetchSmartAlerts();
    // Auto refresh every 2 minutes
    _timer = Timer.periodic(const Duration(minutes: 2), (timer) {
      fetchRealtimeData();
      fetchSmartAlerts();
    });
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  Future<void> fetchRealtimeData() async {
    try {
      var res = await CRUD().get(link: AppLink.realtimeDashboardV2, payload: {});
      if (res != 'failure' && res != null) {
        var d = res is String ? jsonDecode(res) : res;
        if (d['status'] == 'success') {
          realtimeData = d['message'];
          isLoading = false;
          update();
        }
      }
    } catch (e) {
      Log.print('Error fetching realtime dashboard: $e');
    }
  }

  Future<void> fetchSmartAlerts() async {
    try {
      var res = await CRUD().get(link: AppLink.smartAlertsV2, payload: {});
      if (res != 'failure' && res != null) {
        var d = res is String ? jsonDecode(res) : res;
        if (d['status'] == 'success') {
          smartAlerts = d['message'];
          update();
        }
      }
    } catch (e) {
      Log.print('Error fetching smart alerts: $e');
    }
  }
}
