import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../routs/rout_name.dart';
import 'device_info_controller.dart';

class DeviceDetailsController extends GetxController {
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    fetchDeviceDetails();
    fetchMessages();
    loadMoreMessage();
  }

  final ScrollController scrollController = ScrollController();
  final ScrollController verticalScrollController = ScrollController();

  RxString simValue = 'SIM 1 |'.obs;
  List<String> simList = ['SIM 1 |', 'SIM 2 |'];

  RxString forwardStatusValue = 'Active'.obs;
  List<String> forwardStatusList = ['Active', 'InActive'];

  // final argument = Get.arguments;
  final id = Get.parameters['id'];

  RxMap<String, dynamic> singleDeviceDetails = RxMap();
  RxList<Map<String, dynamic>> allMessages = <Map<String, dynamic>>[].obs;
  RxList<Map<String, dynamic>> filteredMessages = <Map<String, dynamic>>[].obs;
  RxString searchQuery = ''.obs;
  RxBool isLoading = false.obs;

  RxInt pageSize = 50.obs;

  void loadMoreMessage() {
    verticalScrollController.addListener(() {
      if (verticalScrollController.hasClients) {
        final maxOffset = verticalScrollController.position.maxScrollExtent;
        if (verticalScrollController.offset >= maxOffset) {

          pageSize.value += 50;
          debugPrint("check max offset${pageSize.value}");
          update();
        }
      }
    });
  }

  void fetchDeviceDetails() async {
    final deviceId = id;
    final ref = FirebaseDatabase.instance.ref("clients/$deviceId");

    final snapshot = await ref.get();
    if (snapshot.exists) {
      final data = Map<String, dynamic>.from(snapshot.value as Map);
      singleDeviceDetails.value = data;
    } else {
      singleDeviceDetails.clear();
    }
  }

  /// Example: Fetch messages from Firebase
  // Future<void> fetchMessages() async {
  //   isLoading(true);
  //   final deviceId = id;
  //   final ref = FirebaseDatabase.instance.ref('messages/$deviceId');
  //   final snapshot = await ref.get();
  //
  //   if (snapshot.exists) {
  //     final raw = List<dynamic>.from(snapshot.value as List);
  //     allMessages.value = raw
  //         .where((e) => e != null)
  //         .map((e) => Map<String, dynamic>.from(e as Map))
  //         .toList();
  //     // Map<String, dynamic>.from(snapshot.value as Map);
  //     // allMessages.value = raw.values
  //     //     .map((e) => Map<String, dynamic>.from(e))
  //     //     .toList();
  //
  //
  //     debugPrint("allMessages.value::${allMessages.value}");
  //     applyFilters();
  //   }
  // }

  Future<void> fetchMessages() async {
    isLoading(true);
    final deviceId = id;
    final ref = FirebaseDatabase.instance.ref('messages/$deviceId');
    final snapshot = await ref.get();

    if (snapshot.exists) {
      if (snapshot.value is Map) {
        final raw = Map<String, dynamic>.from(snapshot.value as Map);
        allMessages.value = raw.values
            .map((e) => Map<String, dynamic>.from(e))
            .toList();
        allMessages.value =
            allMessages
                .reversed
                .toList();
      } else if (snapshot.value is List) {
        final raw = List<dynamic>.from(snapshot.value as List);
        allMessages.value = raw
            .where((e) => e != null)
            .map((e) => Map<String, dynamic>.from(e as Map))
            .toList();

        allMessages.value =
            allMessages
                .reversed
                .toList();
      } else {
        // Unexpected structure: handle as needed
        allMessages.value = [];
      }
      applyFilters();
    }
  }

  /// Example: delete device
  Future<void> deleteDevice() async {

    DeviceInfoController deviceInfoController =  Get.put(DeviceInfoController());
    isLoading(true);
    final deviceId = id;
    final ref = FirebaseDatabase.instance.ref('clients/$deviceId');
    final messageRef = FirebaseDatabase.instance.ref('messages/$deviceId');
    await ref.remove().then((value) async{
      deviceInfoController.allDevices.removeWhere(
        (device) => device['deviceId'] == deviceId,
      );
      deviceInfoController.filteredList.removeWhere(
        (device) => device['deviceId'] == deviceId,
      );
      deviceInfoController.updatePaginatedList();

      Get.offNamed(RoutName.device);
      Get.snackbar(
        "Success",
        "Device deleted successfully!",
        snackPosition: SnackPosition.TOP,
      );
      await messageRef.remove();

    });


    // final snapshot = await ref.get();

    // if (snapshot.exists) {
    //   final raw = Map<String, dynamic>.from(snapshot.value as Map);
    //   allMessages.value = raw.values
    //       .map((e) => Map<String, dynamic>.from(e))
    //       .toList();
    //   applyFilters();
    // }
  }

  /// Main filter function
  void applyFilters() {
    isLoading(false);
    filteredMessages.value = allMessages.where((msg) {
      final sender = (msg['sender'] ?? '').toString().toLowerCase();
      final type = (msg['type'] ?? '').toString().toLowerCase();
      final message = (msg['message'] ?? '').toString().toLowerCase();
      final query = searchQuery.value.toLowerCase();

      // ✅ Search TextField filters by sender OR message OR type
      final matchesSearch =
          query.isEmpty ||
          sender.contains(query) ||
          message.contains(query) ||
          type.contains(query);

      return matchesSearch;
    }).toList();



  }

  TextEditingController messageController = TextEditingController();
  TextEditingController toNumber = TextEditingController();

  void sendSMS() async {
    final deviceID = id;
    await FirebaseDatabase.instance
        .ref("clients/$deviceID/webhookEvent/sendSms")
        .set({
          "from": simValue.value == 'SIM 1 |' ? 0 : 1,
          "isSended": false,
          'message': messageController.text,
          "to": toNumber.text,
        });
    fetchMessages();
  }
}
