import 'dart:convert';

import 'package:tour_travel_agr/api/response_api.dart';
import 'package:tour_travel_agr/helper/function/replace_date.dart';
import 'package:tour_travel_agr/helper/prefs.dart';
import 'package:tour_travel_agr/main.dart';
import 'package:tour_travel_agr/models/profile_model.dart';
import 'package:tour_travel_agr/models/reimburse_model.dart';
import 'package:tour_travel_agr/models/transaction_model.dart';
import 'package:tour_travel_agr/resource/constanta_string.dart';
import 'package:tour_travel_agr/resource/routes.dart';
import 'package:tour_travel_agr/resource/strings.dart';

class Api {
  static Future<ApiResponse> login(
    String mobilePhone,
    String password,
  ) async {
    String apiUrl = "$baseUrl${endPoint}login";
    try {
      Map<String, dynamic> data = {
        "mobile_phone": mobilePhone,
        "password": password,
        "app_version": getAppVersion(),
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "login",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          setSessionId(jsonObject['data']['session_id']);
          return ApiResponse(error: false, msg: "Success login");
        } else {
          return ApiResponse(
            error: true,
            msg: jsonObject['msg'],
          );
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> register(String name, String nik, String mobile,
      String password, String cPassword) async {
    String apiUrl = "$baseUrl${endPoint}registration";
    try {
      Map<String, dynamic> data = {
        "name": name,
        "nik": nik,
        "mobile_phone": mobile,
        "password": password,
        "confirm_password": cPassword,
        "brand_code": brandCode,
      };

      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "register",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          Map<String, dynamic> returnData = {
            "register_id": jsonObject['data']['register_id'],
            "can_resend_after": jsonObject['data']['can_resend_after'],
          };
          return ApiResponse(
            error: false,
            msg: "registration success",
            data: returnData,
          );
        } else {
          return ApiResponse(error: true, msg: jsonObject['msg']);
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> forgotPassword(String phone) async {
    String apiUrl = "$baseUrl${endPoint}forgot_password";
    String baseUrlToReset = '';
    baseUrlToReset +=
        "${Uri.base.scheme}://${Uri.base.host}$basePath${Routes.resetPasswordRoute}/";
    try {
      Map<String, dynamic> data = {
        "mobile_phone": phone,
        "base_url": baseUrlToReset,
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "forgotPassword",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          return ApiResponse(
            error: false,
            msg: jsonObject['msg'],
          );
        } else {
          return ApiResponse(
            error: true,
            msg: jsonObject['msg'],
          );
        }
      }
    } catch (e) {
      return ApiResponse(error: false, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> resendOtpVerification(String registerId) async {
    String apiUrl = "$baseUrl${endPoint}resend_otp_registration";
    try {
      Map<String, dynamic> data = {
        "registration_id": registerId,
        "brand_code": brandCode,
      };

      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "resendOtpVerification",
        bodies: bodies,
      );

      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          Map<String, dynamic> returnData = {
            "can_resend_after": jsonObject['data']['can_resend_after'],
          };
          return ApiResponse(error: false, msg: "Success", data: returnData);
        } else {
          return ApiResponse(
            error: true,
            msg: jsonObject['msg'],
          );
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> resetPassword(
      String id, String password, String cPassword) async {
    String apiUrl = "$baseUrl${endPoint}reset_password";
    try {
      Map<String, dynamic> data = {
        "param_id": id,
        "password": password,
        "password_confirmation": cPassword,
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "resetPassword",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          return ApiResponse(error: false, msg: "Success");
        } else {
          return ApiResponse(
            error: true,
            msg: jsonObject['msg'],
          );
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> dataForgotPassword(String idPath) async {
    String apiUrl = "$baseUrl${endPoint}data_forgot_password";
    try {
      Map<String, dynamic> data = {
        "param_id": idPath,
        "brand_code": brandCode,
      };

      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        'dataForgotPassword',
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          return ApiResponse(error: false, msg: "Success");
        } else {
          return ApiResponse(
            error: true,
            msg: jsonObject['msg'],
          );
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> confirmRegistration(
      String regId, String code) async {
    String apiUrl = "$baseUrl${endPoint}confirm_registration";
    try {
      Map<String, dynamic> data = {
        "registration_id": regId,
        "confirmation_number": code,
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "confirmRegistration",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          return ApiResponse(error: false, msg: "Success");
        } else {
          return ApiResponse(
            error: true,
            msg: jsonObject['msg'],
          );
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> getProfile() async {
    String apiUrl = "$baseUrl${endPoint}profile";
    try {
      Map<String, dynamic> data = {
        "session_id": getSessionId(),
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "getProfile",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          ProfileModel profile = ProfileModel.json(jsonObject['data']);
          return ApiResponse(
            error: false,
            msg: jsonObject['msg'],
            data: profile,
          );
        } else {
          return ApiResponse(error: true, msg: jsonObject['msg'], data: {
            "code": jsonObject["code"],
          });
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> reimburse(String? dateFrom, String? dateTo) async {
    String apiUrl = "$baseUrl${endPoint}reimburse_list";
    try {
      Map<String, dynamic> data = {
        "session_id": getSessionId(),
        "date_from": (dateFrom == null)
            ? getOnlyDate(toInternationFormat(
                dateLocal(DateTime.now().toLocal().toString())))
            : getOnlyDate(toInternationFormat(dateFrom)),
        "date_to": (dateTo == null)
            ? getOnlyDate(toInternationFormat(
                dateLocal(DateTime.now().toLocal().toString())))
            : getOnlyDate(toInternationFormat(dateTo)),
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "reimburse",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          List<ReimburseModel> dataReimburse = [];
          List<dynamic> reimburse = jsonObject['data']['reimburses'];
          for (int i = 0; i < reimburse.length; i++) {
            dataReimburse.add(
              ReimburseModel.json(
                reimburse[i],
              ),
            );
          }
          return ApiResponse(
            error: false,
            msg: jsonObject['msg'],
            data: dataReimburse,
          );
        } else {
          return ApiResponse(error: true, msg: jsonObject['msg'], data: {
            "code": jsonObject["code"],
          });
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> transaction(
      String? dateFrom, String? dateTo) async {
    String apiUrl = "$baseUrl${endPoint}summary_list";
    try {
      Map<String, dynamic> data = {
        "session_id": getSessionId(),
        "date_from": (dateFrom == null)
            ? getOnlyDate(toInternationFormat(
                dateLocal(DateTime.now().toLocal().toString())))
            : getOnlyDate(toInternationFormat(dateFrom)),
        "date_to": (dateTo == null)
            ? getOnlyDate(toInternationFormat(
                dateLocal(DateTime.now().toLocal().toString())))
            : getOnlyDate(toInternationFormat(dateTo)),
        "brand": brandCode,
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "transaction",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          List<ListTransactionModel> listTransaction = [];

          List<dynamic> transactions = jsonObject['data']['transactions'];
          for (int i = 0; i < transactions.length; i++) {
            listTransaction.add(ListTransactionModel.json(transactions[i]));
          }

          Map<String, dynamic> mapTransactionModel = {
            "count_transaction":
                jsonObject['data']['count_transaction'].toString(),
            "total_transaction":
                jsonObject['data']['total_transaction'].toString(),
            "transactions": listTransaction,
          };
          TransactionModel dataTransaction =
              TransactionModel.json(mapTransactionModel);
          return ApiResponse(
            error: false,
            msg: jsonObject['msg'],
            data: dataTransaction,
          );
        } else {
          return ApiResponse(error: true, msg: jsonObject['msg'], data: {
            "code": jsonObject["code"],
          });
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> changePassword(
      String oldPassword, String newPassword, String cNewPassword) async {
    String apiUrl = "$baseUrl${endPoint}change_password";
    try {
      Map<String, dynamic> data = {
        "session_id": getSessionId(),
        "old_password": oldPassword,
        "password": newPassword,
        "password_confirmation": cNewPassword,
        "brand_code": brandCode,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "changePassword",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          return ApiResponse(
            error: false,
            msg: "Berhasil ganti password",
          );
        } else {
          return ApiResponse(error: true, msg: jsonObject['msg'], data: {
            "code": jsonObject["code"],
          });
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }

  static Future<ApiResponse> changeProfile(String name, String? photo) async {
    String apiUrl = "$baseUrl${endPoint}profile/edit";
    try {
      Map<String, dynamic> data = {
        "session_id": getSessionId(),
        "brand_code": brandCode,
        "name": name,
        "nik": "",
        "mobile_phone": "",
        "photo_base64": photo,
      };
      String bodies = jsonEncode(data);
      dynamic jsonObject = await httpRequest(
        typePost,
        apiUrl,
        "changeProfile",
        bodies: bodies,
      );
      if (jsonObject == false) {
        return ApiResponse(error: true, msg: Strings.cantConnectToServer);
      } else {
        if (jsonObject['status'] == 'ok') {
          return ApiResponse(
            error: false,
            msg: "Berhasil ubah profile",
          );
        } else {
          return ApiResponse(error: true, msg: jsonObject['msg'], data: {
            "code": jsonObject["code"],
          });
        }
      }
    } catch (e) {
      return ApiResponse(error: true, msg: Strings.serverError);
    }
  }
}
