// import 'dart:convert';

// import 'package:agrilink_vocpro/core/constant/app_constant.dart';
// import 'package:agrilink_vocpro/core/state/result_state.dart';
// import 'package:mqtt_client/mqtt_client.dart';
// import 'package:mqtt_client/mqtt_server_client.dart';

// class MQTTService {
//   MqttServerClient? client;

//   Future<ResultState> setupMqtt() async {
//     client = MqttServerClient(AppConstant.mqttServer, '');
//     client!.port = 1883;

//     client!.connectionMessage = MqttConnectMessage()
//         .authenticateAs(AppConstant.mqttUsername, AppConstant.mqttPassword)
//         .withClientIdentifier('mobile_client_controller')
//         .startClean() // reset session
//         .withWillQos(MqttQos.atLeastOnce);

//     try {
//       print('MQTT: Connecting....');
//       await client!.connect();
//       print('MQTT: Connected');
//       return ResultState.hasData;
//     } catch (e) {
//       print('MQTT: Error: $e');
//       return ResultState.error;
//     }
//   }

//   Future<ResultState> publishMessage(String topic, String message) async {
//     final builder = MqttClientPayloadBuilder();

//     try {
//       final bool isConnected = await isMqttConnected(); // Cek apakah terhubung
//       if (!isConnected) {
//         print('MQTT: Tidak terhubung ke broker. Tidak bisa publish message.');
//         return ResultState.error;
//       }

//       print('MQTT: Published message to $topic: $message');
//       builder.addString(message);
//       client!.publishMessage(topic, MqttQos.atMostOnce, builder.payload!);
//       print('MQTT: Message published');
//       return ResultState.hasData;
//     } catch (e) {
//       print('MQTT: Error: $e');
//       return ResultState.error;
//     }
//   }

//   Future<ResultState> disconnectMqtt() async {
//     final bool isConnected = await isMqttConnected();
//     if (isConnected) {
//       print('Memutus koneksi dari broker...');

//       client!.disconnect();

//       await Future.delayed(const Duration(seconds: 1));
//       print('Koneksi telah terputus.');
//       return ResultState.hasData;
//     } else {
//       print('Tidak ada koneksi yang sedang aktif.');
//       return ResultState.error;
//     }
//   }

//   Future<bool> isMqttConnected() async {
//     if (client != null &&
//         client!.connectionStatus!.state == MqttConnectionState.connected) {
//       return true; //connected
//     } else {
//       return false; //not connected
//     }
//   }

//   Future<bool> subscribeToTopic(String topic) async {
//     bool isActive = false;
//     if (client != null &&
//         client!.connectionStatus!.state == MqttConnectionState.connected) {
//       try {
//         print('MQTT: Subscribing to $topic');
//         client!.subscribe(topic, MqttQos.atMostOnce);
//         print('MQTT: Subscribed to $topic');

//         // Tambahkan log ini untuk memastikan bahwa listener dijalankan
//         if (client!.updates != null) {
//           print('MQTT: Listening for updates...');
//         } else {
//           print('MQTT: No updates stream available');
//         }

//         client!.updates!.listen(
//           (List<MqttReceivedMessage<MqttMessage?>>? messages) {
//             print('MQTT: Subscribe Message received!');
//             if (messages != null && messages.isNotEmpty) {
//               final MqttPublishMessage recMessage =
//                   messages[0].payload as MqttPublishMessage;
//               final String payload = MqttPublishPayload.bytesToStringAsString(
//                   recMessage.payload.message);
//               print(
//                   'MQTT: Subscribe Message received on topic ${messages[0].topic}: $payload');

//               if (payload == 'ON') {
//                 isActive = true;
//                 // Update UI atau provider untuk menandakan relay ON
//               } else if (payload == 'OFF') {
//                 isActive = false;
//                 // Update UI atau provider untuk menandakan relay OFF
//               } else {
//                 print('MQTT: Invalid Subscribe message received');
//               }
//             } else {
//               print('MQTT: No Subscribe messages received');
//             }
//           },
//         );

//         return isActive;
//       } catch (e) {
//         print('MQTT: Error subscribing to $topic: $e');
//         return isActive;
//       }
//     } else {
//       print('MQTT: Not connected, cannot subscribe.');
//       return false;
//     }
//   }

//   Future<ResultState> subscribeToRelayStatus() async {
//     if (client != null &&
//         client!.connectionStatus!.state == MqttConnectionState.connected) {
//       try {
//         print('MQTT: Subscribing to /smartfarming/getRelayStatus');
//         client!.subscribe('smartfarming/getRelayStatus', MqttQos.atMostOnce);
//         print('MQTT: Subscribed to /smartfarming/getRelayStatus');

//         client!.updates!
//             .listen((List<MqttReceivedMessage<MqttMessage?>>? messages) {
//           if (messages != null && messages.isNotEmpty) {
//             final MqttPublishMessage recMessage =
//                 messages[0].payload as MqttPublishMessage;
//             final String payload = MqttPublishPayload.bytesToStringAsString(
//                 recMessage.payload.message);
//             print(
//                 'MQTT: Message received on topic ${messages[0].topic}: $payload');

//             // Parse the received JSON payload
//             final Map<String, dynamic> relayStatus = jsonDecode(payload);

//             print('MQTT: Relay status: $relayStatus');

//             // Assuming you are using provider, notify it with new relay status
//             // _updateRelayStatus(relayStatus);
//           } else {
//             print('MQTT: No messages received');
//           }
//         });
//         return ResultState.hasData;
//       } catch (e) {
//         print('MQTT: Error subscribing: $e');
//         return ResultState.error;
//       }
//     } else {
//       print('MQTT: Not connected, cannot subscribe.');
//       return ResultState.error;
//     }
//   }
// }
