import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:sfm_app/feature/log/device_logs_model.dart';
import 'package:sfm_app/product/services/api_services.dart';
import 'package:sfm_app/product/services/language_services.dart';
import 'package:sfm_app/product/shared/model/district_model.dart';
import 'package:sfm_app/product/shared/model/province_model.dart';

import '../../feature/devices/device_model.dart';
import '../shared/model/ward_model.dart';

class DeviceUtils {
  DeviceUtils._init();
  static DeviceUtils? _instance;
  static DeviceUtils get instance => _instance ??= DeviceUtils._init();
  APIServices apiServices = APIServices();

  Map<String, dynamic> getDeviceSensors(
      BuildContext context, List<Sensor> sensors) {
    Map<String, dynamic> map = {};
    if (sensors.isEmpty) {
      map['sensorState'] = appLocalization(context).no_data_message;
      map['sensorBattery'] = appLocalization(context).no_data_message;
      map['sensorCsq'] = appLocalization(context).no_data_message;
      map['sensorTemp'] = appLocalization(context).no_data_message;
      map['sensorHum'] = appLocalization(context).no_data_message;
      map['sensorVolt'] = appLocalization(context).no_data_message;
    } else {
      for (var sensor in sensors) {
        if (sensor.name == "1") {
          if (sensor.value == 0) {
            map['sensorIn'] = "sensor 0";
          } else {
            map['sensorIn'] = "sensor 1";
          }
        }
        if (sensor.name == "2") {
          if (sensor.value == 0) {
            map['sensorMove'] = appLocalization(context).gf_not_move_message;
          } else {
            map['sensorMove'] = appLocalization(context).gf_moving_message;
          }
        }
        if (sensor.name == "3") {
          if (sensor.value == 0) {
            map['sensorAlarm'] = appLocalization(context).normal_message;
          } else {
            map['sensorAlarm'] =
                appLocalization(context).warning_status_message;
          }
        }
        if (sensor.name == "6") {
          if (sensor.value! > 0 && sensor.value! < 12) {
            map['sensorCsq'] = appLocalization(context).low_message_uppercase;
          } else if (sensor.value! >= 12 && sensor.value! < 20) {
            map['sensorCsq'] =
                appLocalization(context).moderate_message_uppercase;
          } else if (sensor.value! >= 20) {
            map['sensorCsq'] = appLocalization(context).good_message_uppercase;
          } else {
            map['sensorCsq'] = appLocalization(context).gf_no_signal_message;
          }
        }
        if (sensor.name == "7") {
          map['sensorVolt'] = "${(sensor.value!) / 1000} V";
        }
        if (sensor.name == "8") {
          map['sensorTemp'] = "${sensor.value}°C";
        }
        if (sensor.name == "9") {
          map['sensorHum'] = "${sensor.value} %";
        }
        if (sensor.name == "10") {
          map['sensorBattery'] = "${sensor.value}";
        }
        if (sensor.name == "11") {
          if (sensor.value == 0) {
            map['sensorState'] = appLocalization(context).normal_message;
          } else if (sensor.value == 1) {
            map['sensorState'] =
                appLocalization(context).smoke_detecting_message;
          } else if (sensor.value == 3) {
            map['sensorState'] =
                appLocalization(context).gf_remove_from_base_message;
          } else {
            map['sensorState'] = appLocalization(context).undefine_message;
          }
        }
      }
    }
    return map;
  }

  Future<String> getFullDeviceLocation(
      BuildContext context, String areaPath) async {
    if (areaPath != "") {
      List<String> parts = areaPath.split('_');

      String provinceID = parts[0];
      String districtID = parts[1];
      String wardID = parts[2];

      String provinceBody = await apiServices.getProvinceByID(provinceID);
      final provinceItem = jsonDecode(provinceBody);
      Province province = Province.fromJson(provinceItem['data']);
      String districtBody = await apiServices.getDistrictByID(districtID);
      final districtItem = jsonDecode(districtBody);
      District district = District.fromJson(districtItem['data']);
      String wardBody = await apiServices.getWardByID(wardID);
      final wardItem = jsonDecode(wardBody);
      Ward ward = Ward.fromJson(wardItem['data']);

      return "${ward.fullName}, ${district.fullName}, ${province.fullName}";
    }
    return appLocalization(context).no_data_message;
  }

  String checkStateDevice(BuildContext context, int state) {
    String message = appLocalization(context).no_data_message;
    if (state == 1) {
      message = appLocalization(context).smoke_detecting_message;
    } else if (state == 0) {
      message = appLocalization(context).normal_message;
    } else if (state == -1) {
      message = appLocalization(context).disconnect_message_uppercase;
    } else if (state == 2) {
      message = appLocalization(context).in_progress_message;
    } else if (state == 3) {
      message = appLocalization(context).in_progress_message;
    }
    return message;
  }

  List<Device> sortDeviceByState(List<Device> devices) {
    List<Device> sortedDevices = List.from(devices);
    sortedDevices.sort((a, b) {
      int stateOrder = [2, 1, 3, 0, -1, 3].indexOf(a.state!) -
          [2, 1, 3, 0, -1, 3].indexOf(b.state!);
      return stateOrder;
    });

    return sortedDevices;
  }

  Color getTableRowColor(int state) {
    if (state == 1) {
      return Colors.red;
    } else if (state == 0) {
      return Colors.green;
    } else {
      return Colors.grey;
    }
  }

  String getDeviceSensorsLog(BuildContext context, SensorLogs sensor) {
    String message = "";
    if (sensor.detail!.username != null || sensor.detail!.note != null) {
      message = "${appLocalization(context).bell_user_uppercase} ";
      if (sensor.name! == "0") {
        if (sensor.value! == 3) {
          String state = "đã thông báo rằng đây là cháy giả";
          message = message + state;
        }
      }
    } else {
      message = "${appLocalization(context).device_title} ";
      if (sensor.name == "11") {
        String state = checkStateDevice(context, sensor.value!);
        message = message + state;
      } else if (sensor.name == "2") {
        String state = getDeviceMove(context, sensor.value!);
        message = message + state;
      } else if (sensor.name == "6") {
        String state = getDeviceCSQ(context, sensor.value!);
        message = message + state;
      } else if (sensor.name == "7") {
        String state = getDeviceVolt(context, sensor.value!);
        message = message + state;
      } else if (sensor.name == "8") {
        String state = getDeviceTemp(context, sensor.value!);
        message = message + state;
      } else if (sensor.name == "9") {
        String state = getDeviceHum(context, sensor.value!);
        message = message + state;
      } else if (sensor.name == "10") {
        String state = getDeviceBattery(context, sensor.value!);
        message = message + state;
      } else {
        String state = appLocalization(context).undefine_message;
        message = message + state;
      }
    }
    return message;
  }

  String getDeviceCSQ(BuildContext context, int number) {
    if (number >= 0 && number < 12) {
      return appLocalization(context).gf_weak_signal_message;
    } else if (number >= 12 && number < 20) {
      return appLocalization(context).gf_moderate_signal_message;
    } else if (number >= 20) {
      return appLocalization(context).gf_good_signal_message;
    }
    return appLocalization(context).gf_no_signal_message;
  }

  String getDeviceVolt(BuildContext context, int number) {
    return "${appLocalization(context).gf_volt_detect_message} ${number / 1000} V";
  }

  String getDeviceTemp(BuildContext context, int number) {
    return "${appLocalization(context).gf_temp_detect_message} $number °C";
  }

  String getDeviceHum(BuildContext context, int number) {
    return "${appLocalization(context).gf_hum_detect_message} $number%";
  }

  String getDeviceBattery(BuildContext context, int number) {
    return "${appLocalization(context).gf_battery_detect_message} $number%";
  }

  String getDeviceMove(BuildContext context, int number) {
    String message = "";
    if (number == 0) {
      message = appLocalization(context).gf_not_move_message;
    } else {
      message = appLocalization(context).gf_moving_message;
    }
    return message;
  }

  IconData getBatteryIcon(int battery) {
    if (battery <= 10) {
      return Icons.battery_alert;
    } else if (battery <= 40) {
      return Icons.battery_2_bar;
    } else if (battery <= 70) {
      return Icons.battery_4_bar;
    } else if (battery <= 90) {
      return Icons.battery_6_bar;
    } else {
      return Icons.battery_full_rounded;
    }
  }

  IconData getSignalIcon(BuildContext context, String signal) {
    if (signal == appLocalization(context).gf_weak_signal_message) {
      return Icons.signal_cellular_alt_1_bar;
    } else if (signal == appLocalization(context).gf_moderate_signal_message) {
      return Icons.signal_cellular_alt_2_bar;
    } else {
      return Icons.signal_cellular_alt;
    }
  }

  Color getColorRiple(int state) {
    if (state == 1) {
      return Colors.red;
    } else if (state == 3) {
      return Colors.orange;
    } else if (state == -1) {
      return Colors.grey;
    } else {
      return Colors.green;
    }
  }
}
