import 'package:firebase_database/firebase_database.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../models/MyFiles.dart';
import '../utils/App_color.dart';
import 'package:flutter/material.dart';

class DashBoardController extends GetxController {
  final _db = FirebaseDatabase.instance.ref('clients');

  @override
  void onInit() async {
    super.onInit();
    // totalCount.value =
    await fetchDeviceStats();
    fetchUserDetails();
  }

  // RxMap<String, int> totalCount = {
  //   'total': 0,
  //   'online': 0,
  //   'offline': 0,
  //   'today': 0,
  // }.obs;

  Future<Map<String, int>> fetchDeviceStats() async {
    final snapshot = await _db.get();

    if (!snapshot.exists)
      return {'total': 0, 'online': 0, 'offline': 0, 'today': 0};

    int total = 0;
    int online = 0;
    int offline = 0;
    int today = 0;

    final todayDate = DateFormat('dd/MM/yyyy').format(DateTime.now());

    for (final device in snapshot.children) {
      total++;

      final data = device.value as Map<dynamic, dynamic>;
      final bool status = data['status'] == true;
      final String joined = data['joined'] ?? '';

      if (status) {
        online++;
      } else {
        offline++;
      }

      // Extract date from "18/10/2025 | 09:42 PM"
      final datePart = joined.split('|').first.trim();
      if (datePart == todayDate) {
        today++;
      }
    }

    debugPrint('total device::${total}');
    countersList[0].totalDevice = total;
    countersList[1].totalDevice = online;
    countersList[2].totalDevice = offline;
    countersList[3].totalDevice = today;
    update();

    return {
      'total': total,
      'online': online,
      'offline': offline,
      'today': today,
    };
  }

  RxList<CloudStorageInfo> countersList = [
    CloudStorageInfo(
      title: "Total Device",
      svgSrc: "assets/icons/ic_mobile.svg",
      totalDevice: 0,
      color: AppColor.primaryColor,
    ),
    CloudStorageInfo(
      title: "Online Device",
      svgSrc: "assets/icons/ic_wifi.svg",
      totalDevice: 0,
      color: Color(0xFF32FF13),
    ),
    CloudStorageInfo(
      title: "Offline Device",
      svgSrc: "assets/icons/ic_power.svg",
      totalDevice: 0,
      color: Color(0xFFFD5690),
    ),
    CloudStorageInfo(
      title: "Today's Devices",
      svgSrc: "assets/icons/ic_wave.svg",
      totalDevice: 0,
      color: Color(0xFF00E5A8),
    ),
  ].obs;

  RxMap<String, dynamic> userDetails = RxMap();

  void fetchUserDetails() async {
    final ref = FirebaseDatabase.instance.ref("user");

    final snapshot = await ref.get();
    if (snapshot.exists) {
      final data = Map<String, dynamic>.from(snapshot.value as Map);
      userDetails.value = data;
      if (data['emi'] != null) {
        final List emiList = data['emi'] as List;

        // Convert each LinkedMap inside `emi` into a proper Map<String, dynamic>
        data['emi'] = emiList
            .map((e) => Map<String, dynamic>.from(e as Map))
            .toList();
      }

      debugPrint("userDetails::${userDetails}");
    } else {
      userDetails.clear();
    }
  }
}
