import 'dart:async';

import 'package:get/get.dart';
import 'package:sefer_admin1/constant/links.dart';

import '../../print.dart';

// --- Models ---

class ServerData {
  final CpuInfo cpu;
  final MemoryInfo memory;
  final DiskInfo disk;
  final Map<String, String> services;
  final List<ProcessInfo> topProcesses;
  final NetworkInfo network;
  final UptimeInfo uptime;
  final String timestamp;

  ServerData({
    required this.cpu,
    required this.memory,
    required this.disk,
    required this.services,
    required this.topProcesses,
    required this.network,
    required this.uptime,
    required this.timestamp,
  });

  factory ServerData.fromJson(Map<String, dynamic> json) {
    return ServerData(
      cpu: CpuInfo.fromJson(json['cpu']),
      memory: MemoryInfo.fromJson(json['memory']),
      disk: DiskInfo.fromJson(json['disk']),
      services: Map<String, String>.from(json['services']),
      topProcesses: (json['top_processes'] as List)
          .map((i) => ProcessInfo.fromJson(i))
          .toList(),
      network: NetworkInfo.fromJson(json['network']),
      uptime: UptimeInfo.fromJson(json['uptime']),
      timestamp: json['timestamp'],
    );
  }
}

class CpuInfo {
  final double percent;
  final int cores;
  final double load1m;
  CpuInfo({required this.percent, required this.cores, required this.load1m});
  factory CpuInfo.fromJson(Map<String, dynamic> json) => CpuInfo(
      percent: json['percent'].toDouble(),
      cores: json['cores'],
      load1m: json['load_1m'].toDouble());
}

class MemoryInfo {
  final double percent;
  final double usedGb;
  final double totalGb;
  MemoryInfo(
      {required this.percent, required this.usedGb, required this.totalGb});
  factory MemoryInfo.fromJson(Map<String, dynamic> json) => MemoryInfo(
      percent: json['percent'].toDouble(),
      usedGb: json['used_gb'].toDouble(),
      totalGb: json['total_gb'].toDouble());
}

class DiskInfo {
  final double percent;
  final double usedGb;
  final double totalGb;
  DiskInfo(
      {required this.percent, required this.usedGb, required this.totalGb});
  factory DiskInfo.fromJson(Map<String, dynamic> json) => DiskInfo(
      percent: json['percent'].toDouble(),
      usedGb: json['used_gb'].toDouble(),
      totalGb: json['total_gb'].toDouble());
}

class ProcessInfo {
  final String name;
  final String usage;
  ProcessInfo({required this.name, required this.usage});
  factory ProcessInfo.fromJson(Map<String, dynamic> json) =>
      ProcessInfo(name: json['name'], usage: json['usage']);
}

class NetworkInfo {
  final double receivedMb;
  final double sentMb;
  NetworkInfo({required this.receivedMb, required this.sentMb});
  factory NetworkInfo.fromJson(Map<String, dynamic> json) => NetworkInfo(
      receivedMb: json['received_mb'].toDouble(),
      sentMb: json['sent_mb'].toDouble());
}

class UptimeInfo {
  final String formatted;
  UptimeInfo({required this.formatted});
  factory UptimeInfo.fromJson(Map<String, dynamic> json) =>
      UptimeInfo(formatted: json['formatted']);
}

// --- Controller ---

class ServerMonitorController extends GetxController {
  var isLoading = false.obs;
  var serverData = Rxn<ServerData>();
  var errorMessage = ''.obs;

  Timer? _timer; // تخزين التايمر

  @override
  void onInit() {
    super.onInit();
    fetchServerData();
    // تحديث تلقائي كل 60 ثانية
    _timer = Timer.periodic(Duration(seconds: 60), (_) {
      fetchServerData();
    });
  }

  @override
  void onClose() {
    // إلغاء التحديث عند إغلاق الصفحة
    _timer?.cancel();
    super.onClose();
  }

  Future<void> fetchServerData() async {
    try {
      isLoading(true);
      errorMessage('');

      final response = await GetConnect().get(AppLink.serverMonitor);

      if (response.status.hasError) {
        errorMessage.value = 'خطأ في الاتصال: ${response.statusText}';
      } else {
        serverData.value = ServerData.fromJson(response.body);
      }
    } catch (e) {
      errorMessage.value = 'حدث خطأ: $e';
    } finally {
      isLoading(false);
    }
  }
}
