// ignore_for_file: use_build_context_synchronously

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import '../constant/app/api_path_constant.dart';
import '../shared/shared_snack_bar.dart';
import '../constant/enums/app_route_enums.dart';
import 'language_services.dart';
import '../../feature/bell/bell_model.dart';
import '../cache/local_manager.dart';
import '../constant/app/app_constants.dart';
import '../constant/enums/local_keys_enums.dart';
import '../network/network_manager.dart';

class APIServices {
  Map<String, String> headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    "Access-Control-Allow-Credentials": "false",
    "Access-Control-Allow-Headers":
        "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
    'Access-Control-Allow-Origin': "*",
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
  };

  Future<Map<String, String>> getHeaders() async {
    String? token =
        LocaleManager.instance.getStringValue(PreferencesKeys.TOKEN);
    Map<String, String> headers = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      "Access-Control-Allow-Credentials": "false",
      "Access-Control-Allow-Headers":
          "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
      'Access-Control-Allow-Origin': "*",
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
      'Authorization': token,
    };
    return headers;
  }

  Future<String> login(String path, Map<String, dynamic> loginRequest) async {
    final url = Uri.https(ApplicationConstants.DOMAIN, path);
    final headers = await getHeaders();
    final response =
        await http.post(url, headers: headers, body: jsonEncode(loginRequest));
    return response.body;
  }

  Future<void> logOut(BuildContext context) async {
    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text(appLocalization(context).log_out_content,
                  textAlign: TextAlign.center),
              actions: [
                TextButton(
                  onPressed: () async {
                    var url = Uri.http(ApplicationConstants.DOMAIN,
                        APIPathConstants.LOGOUT_PATH);
                    final headers = await NetworkManager.instance!.getHeaders();
                    final response = await http.post(url, headers: headers);
                    if (response.statusCode == 200) {
                      LocaleManager.instance
                          .deleteStringValue(PreferencesKeys.UID);
                      LocaleManager.instance
                          .deleteStringValue(PreferencesKeys.TOKEN);
                      LocaleManager.instance
                          .deleteStringValue(PreferencesKeys.EXP);
                      LocaleManager.instance
                          .deleteStringValue(PreferencesKeys.ROLE);
                      context.goNamed(AppRoutes.LOGIN.name);
                    } else {
                      showErrorTopSnackBarCustom(
                          context, "Error: ${response.statusCode}");
                    }
                  },
                  child: Text(appLocalization(context).log_out,
                      style: const TextStyle(color: Colors.red)),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(appLocalization(context).cancel_button_content),
                ),
              ],
            ));
  }

  Future<String> getUID() async {
    String uid = LocaleManager.instance.getStringValue(PreferencesKeys.UID);
    return uid;
  }

  Future<String> getUserRole() async {
    String role = LocaleManager.instance.getStringValue(PreferencesKeys.ROLE);
    return role;
  }

  Future<String> checkTheme() async {
    String theme = LocaleManager.instance.getStringValue(PreferencesKeys.THEME);
    return theme;
  }

  Future<String> checkLanguage() async {
    String language =
        LocaleManager.instance.getStringValue(PreferencesKeys.LANGUAGE_CODE);
    return language;
  }

  Future<Bell> getBellNotifications(String offset, String pagesize) async {
    Bell bell = Bell();
    final params = {"offset": offset, "page_size": pagesize};
    final data = await NetworkManager.instance!.getDataFromServerWithParams(
        APIPathConstants.BELL_NOTIFICATIONS_PATH, params);
    if (data != "") {
      bell = Bell.fromJson(jsonDecode(data));
      return bell;
    } else {
      return bell;
    }
  }

  Future<int> updateStatusOfNotification(List<String> notificationID) async {
    Map<String, dynamic> body = {
      "event_ids": notificationID,
    };
    int statusCode = await NetworkManager.instance!.updateDataInServer(
        APIPathConstants.BELL_UPDATE_READ_NOTIFICATIONS_PATH, body);
    return statusCode;
  }

  Future<String> getUserDetail() async {
    String uid = await getUID();
    String? response = await NetworkManager.instance!
        .getDataFromServer('${APIPathConstants.USER_PATH}/$uid');
    return response;
  }

  Future<int> updateUserProfile(Map<String, dynamic> body) async {
    String uid = await getUID();
    int statusCode = await NetworkManager.instance!
        .updateDataInServer("${APIPathConstants.USER_PROFILE_PATH}/$uid", body);
    return statusCode;
  }

  Future<int> updateUserPassword(Map<String, dynamic> body) async {
    String uid = await getUID();
    int statusCode = await NetworkManager.instance!.updateDataInServer(
        "${APIPathConstants.USER_PATH}/$uid/password", body);
    return statusCode;
  }

  Future<String> getAllSettingsNotificationOfDevices() async {
    String? data = await NetworkManager.instance!
        .getDataFromServer(APIPathConstants.DEVICE_NOTIFICATION_SETTINGS);
    return data;
  }

  Future<int> updateDeviceNotificationSettings(
      String thingID, Map<String, int> data) async {
    Map<String, dynamic> body = {"thing_id": thingID, "notifi_settings": data};
    int statusCode = await NetworkManager.instance!.updateDataInServer(
        APIPathConstants.DEVICE_NOTIFICATION_SETTINGS, body);
    return statusCode;
  }

  Future<String> getDashBoardDevices() async {
    String? data = await NetworkManager.instance!
        .getDataFromServer(APIPathConstants.DASHBOARD_DEVICES);
    return data;
  }

  Future<int> setupDeviceNotification(String thingID, String deviceName) async {
    Map<String, dynamic> body = {
      "thing_id": thingID,
      "alias": deviceName,
      "notifi_settings": {
        "001": 1,
        "002": 1,
        "003": 1,
        "004": 1,
        "005": 1,
        "006": 1,
        "101": 1,
        "102": 1,
        "103": 1,
        "104": 1,
      }
    };
    int statusCode = await NetworkManager.instance!.updateDataInServer(
        APIPathConstants.DEVICE_NOTIFICATION_SETTINGS, body);
    return statusCode;
  }

  Future<String> getAllProvinces() async {
    String? data = await NetworkManager.instance!
        .getDataFromServer(APIPathConstants.PROVINCES_PATH);
    return data;
  }

  Future<String> getProvincesByName(String name) async {
    final params = {'name': name};
    String? data = await NetworkManager.instance!
        .getDataFromServerWithParams(APIPathConstants.PROVINCES_PATH, params);
    return data;
  }

  Future<String> getProvinceByID(String provinceID) async {
    String data = await NetworkManager.instance!
        .getDataFromServer("${APIPathConstants.PROVINCES_PATH}/$provinceID");
    return data;
  }

  Future<String> getAllDistricts(String provinceID) async {
    final params = {"parent": provinceID};
    String? data = await NetworkManager.instance!
        .getDataFromServerWithParams(APIPathConstants.DISTRICTS_PATH, params);
    return data;
  }

  Future<String> getDistrictsByName(String districtName) async {
    final params = {"name": districtName};
    String? data = await NetworkManager.instance!
        .getDataFromServerWithParams(APIPathConstants.DISTRICTS_PATH, params);
    return data;
  }

  Future<String> getDistrictByID(String districtID) async {
    String? data = await NetworkManager.instance!
        .getDataFromServer("${APIPathConstants.DISTRICTS_PATH}/$districtID");
    return data;
  }

  Future<String> getAllWards(String districtID) async {
    final params = {'parent': districtID};
    String? data = await NetworkManager.instance!
        .getDataFromServerWithParams(APIPathConstants.WARDS_PATH, params);
    return data;
  }

  Future<String> getWarsdByName(String wardName) async {
    final params = {"name": wardName};
    String? data = await NetworkManager.instance!
        .getDataFromServerWithParams(APIPathConstants.WARDS_PATH, params);
    return data;
  }

  Future<String> getWardByID(String wardID) async {
    String? data = await NetworkManager.instance!
        .getDataFromServer("${APIPathConstants.WARDS_PATH}/$wardID");
    return data;
  }

  Future<int> confirmFakeFireByUser(String thingID) async {
    Map<String, dynamic> body = {
      "state": 3,
      "note": "Người dùng xác nhận cháy giả!"
    };
    int statusCode = await NetworkManager.instance!
        .updateDataInServer("${APIPathConstants.DEVICE_PATH}/$thingID", body);
    return statusCode;
  }

  Future<String> getOwnerDevices() async {
    String? data = await NetworkManager.instance!
        .getDataFromServer(APIPathConstants.DEVICE_PATH);
    return data;
  }

  Future<int> createDeviceByAdmin(Map<String, dynamic> body) async {
    int? statusCode = await NetworkManager.instance!
        .createDataInServer(APIPathConstants.DEVICE_PATH, body);
    return statusCode;
  }

  Future<int> registerDevice(Map<String, dynamic> body) async {
    int? statusCode = await NetworkManager.instance!
        .createDataInServer(APIPathConstants.DEVICE_REGISTER_PATH, body);
    return statusCode;
  }

  Future<int> deleteDeviceByAdmin(String thingID) async {
    int statusCode = await NetworkManager.instance!
        .deleteDataInServer("${APIPathConstants.DEVICE_PATH}/$thingID");
    return statusCode;
  }

  Future<int> unregisterDevice(Map<String, dynamic> body) async {
    int statusCode = await NetworkManager.instance!
        .createDataInServer(APIPathConstants.DEVICE_UNREGISTER_PATH, body);
    return statusCode;
  }

  Future<String> getDeviceInfomation(String thingID) async {
    String? response = await NetworkManager.instance!
        .getDataFromServer("${APIPathConstants.DEVICE_PATH}/$thingID");
    return response;
  }

  Future<String> getAllGroups() async {
    String? body = await NetworkManager.instance!
        .getDataFromServer(APIPathConstants.ALL_GROUPS_PATH);
    return body;
  }

  Future<int> createGroup(Map<String, dynamic> body) async {
    int? statusCode = await NetworkManager.instance!
        .createDataInServer(APIPathConstants.GROUPS_PATH, body);
    return statusCode;
  }

  Future<int> updateGroup(Map<String, dynamic> body, String groupID) async {
    int? statusCode = await NetworkManager.instance!
        .updateDataInServer("${APIPathConstants.GROUPS_PATH}/$groupID", body);
    return statusCode;
  }

  Future<int> joinGroup(String groupID, Map<String, dynamic> body) async {
    int? statusCode = await NetworkManager.instance!
        .createDataInServer(APIPathConstants.JOIN_GROUP_PATH, body);
    return statusCode;
  }

  Future<int> deleteGroup(String groupID) async {
    int? statusCode = await NetworkManager.instance!
        .deleteDataInServer("${APIPathConstants.GROUPS_PATH}/$groupID");
    return statusCode;
  }

  Future<String> getGroupDetail(String groupID) async {
    String? body = await NetworkManager.instance!
        .getDataFromServer("${APIPathConstants.GROUPS_PATH}/$groupID");
    return body;
  }

  Future<int> approveGroup(Map<String, dynamic> body) async {
    int statusCode = await NetworkManager.instance!
        .createDataInServer(APIPathConstants.APPROVE_GROUP_PATH, body);
    return statusCode;
  }

  Future<int> deleteUserInGroup(String groupID, String userID) async {
    int? statusCode = await NetworkManager.instance!.deleteDataInServer(
        "${APIPathConstants.GROUPS_PATH}/$groupID/users/$userID");
    return statusCode;
  }

  Future<int> deleteDeviceInGroup(String groupID, String thingID) async {
    int? statusCode = await NetworkManager.instance!.deleteDataInServer(
        "${APIPathConstants.GROUPS_PATH}/$groupID/devices/$thingID");
    return statusCode;
  }

  Future<int> updateDeviceAlias(Map<String, dynamic> body) async {
    int? statusCode = await NetworkManager.instance!.updateDataInServer(
        APIPathConstants.DEVICE_NOTIFICATION_SETTINGS, body);
    return statusCode;
  }

  Future<int> addDeviceToGroup(
      String groupID, Map<String, dynamic> body) async {
    int? statusCode = await NetworkManager.instance!.createDataInServer(
        "${APIPathConstants.GROUPS_PATH}/$groupID/things", body);
    return statusCode;
  }

  Future<int> updateOwnerDevice(
      String thingID, Map<String, dynamic> body) async {
    int? statusCode = await NetworkManager.instance!
        .updateDataInServer("${APIPathConstants.DEVICE_PATH}/$thingID", body);
    return statusCode;
  }

  Future<String> getLogsOfDevice(
      String thingID, Map<String, dynamic> params) async {
    String? body = await NetworkManager.instance!
        .getDataFromServerWithParams(APIPathConstants.DEVICE_LOGS_PATH, params);
    return body;
  }
  

}
