import 'dart:io';
import 'package:mypoint_flutter_app/configs/api_paths.dart';
import 'package:mypoint_flutter_app/base/base_response_model.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:mypoint_flutter_app/screen/game/models/game_bundle_response.dart';
import 'package:mypoint_flutter_app/screen/voucher/models/product_model.dart';
import '../configs/device_info.dart';
import '../model/auth/biometric_register_response_model.dart';
import '../model/auth/login_token_response_model.dart';
import '../model/auth/profile_response_model.dart';
import '../model/update_response_model.dart';
import '../preference/point/header_home_model.dart';
import '../screen/faqs/faqs_model.dart';
import '../screen/game/models/game_bundle_item_model.dart';
import '../screen/notification/models/category_notify_item_model.dart';
import '../screen/notification/models/notification_detail_model.dart';
import '../screen/notification/models/notification_list_data_model.dart';
import '../screen/onboarding/model/check_phone_response_model.dart';
import '../screen/onboarding/model/onboarding_info_model.dart';
import '../screen/otp/model/create_otp_response_model.dart';
import '../screen/otp/model/otp_verify_response_model.dart';
import '../screen/pageDetail/model/campaign_detail_model.dart';
import '../screen/pageDetail/model/detail_page_rule_type.dart';
import '../screen/register_campaign/model/registration_form_package_model.dart';
import '../screen/shopping/model/affiliate_brand_model.dart';
import '../screen/shopping/model/affiliate_category_model.dart';
import '../screen/shopping/model/affiliate_product_top_sale_model.dart';
import '../screen/shopping/model/cashback_overview_model.dart';
import '../screen/splash/splash_screen_viewmodel.dart';
import '../screen/transaction/history/transaction_history_model.dart';
import '../screen/transaction/model/order_product_payment_response_model.dart';
import '../screen/transaction/model/payment_bank_account_info_model.dart';
import '../screen/transaction/model/payment_method_model.dart';
import '../screen/transaction/model/payment_method_type.dart';
import '../screen/transaction/model/preview_order_payment_model.dart';
import '../screen/voucher/models/like_product_reponse_model.dart';
import '../screen/voucher/models/product_store_model.dart';
import '../screen/voucher/models/search_product_response_model.dart';
import 'model_maker.dart';

extension RestfullAPIClientAllApi on RestfulAPIClient {
  Future<BaseResponseModel<UpdateResponseModel>> checkUpdateApp() async {
    String version = Platform.version;
    final body = {"operating_system": "iOS", "software_model": "MyPoint", "version": "1.21.7", "build_number": "1"};
    return requestNormal(APIPaths.checkUpdate, Method.POST, body, (data) => UpdateResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<OnboardingInfoModel>> getOnboardingInfo() async {
    return requestNormal(
      APIPaths.getOnboardingInfo,
      Method.GET,
      {},
      (data) => OnboardingInfoModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CheckPhoneResponseModel>> checkPhoneNumber(String phone) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    var key = "$phone+_=$deviceKey/*8854";
    final body = {"device_key": deviceKey, "phone_number": phone, "key": key.toSha256()};
    return requestNormal(
      APIPaths.checkPhoneNumber,
      Method.POST,
      body,
      (data) => CheckPhoneResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<OTPVerifyResponseModel>> verifyOTP(String otp, String mfaToken) async {
    final body = {"otp": otp, "mfaToken": mfaToken};
    return requestNormal(
      APIPaths.verifyOtpWithAction,
      Method.POST,
      body,
      (data) => OTPVerifyResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<OTPResendResponseModel>> resendOTP(String mfaToken) async {
    final body = {"mfaToken": mfaToken};
    return requestNormal(
      APIPaths.retryOtpWithAction,
      Method.POST,
      body,
      (data) => OTPResendResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CreateOTPResponseModel>> requestOtpDeleteAccount() async {
    return requestNormal(
      APIPaths.otpDeleteAccountRequest,
      Method.POST,
      {},
      (data) => CreateOTPResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CreateOTPResponseModel>> verifyDeleteAccount(String otp) async {
    return requestNormal(APIPaths.verifyDeleteAccount, Method.POST, {
      "otp": otp,
    }, (data) => CreateOTPResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<EmptyCodable>> signup(String phone, String password) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {"username": phone, "password": password.toSha256(), "device_key": deviceKey};
    return requestNormal(APIPaths.signup, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json));
  }

  Future<BaseResponseModel<LoginTokenResponseModel>> login(String phone, String password) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {
      "username": phone,
      "password": password.toSha256(),
      "device_key": deviceKey,
      "workspace_code": "8854",
    };
    return requestNormal(APIPaths.login, Method.POST, body, (data) => LoginTokenResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<LoginTokenResponseModel>> loginWithBiometric(String phone) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    var bioToken = await DataPreference.instance.getBioToken(phone) ?? "";
    final body = {"username": phone, "bioToken": bioToken, "deviceKey": deviceKey, "workspaceCode": "8854"};
    return requestNormal(
      APIPaths.loginWithBiometric,
      Method.POST,
      body,
      (data) => LoginTokenResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<ProfileResponseModel>> getUserProfile() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    return requestNormal(APIPaths.getUserInfo, Method.GET, {}, (data) => ProfileResponseModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<CreateOTPResponseModel>> otpCreateNew(String ownerId) async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {"owner_id": ownerId, "ttl": Constants.otpTtl, "resend_after_second": Constants.otpTtl};
    return requestNormal(
      APIPaths.otpCreateNew,
      Method.POST,
      body,
      (data) => CreateOTPResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CreateOTPResponseModel>> otpVerifyForDoingNextEvent(
    String ownerId,
    String otp,
    String nextEventName,
  ) async {
    final body = {
      "owner_id": ownerId,
      "otp": otp,
      "next_event_name": nextEventName,
      "ttdne": 180, //  TODO
      "ttl": Constants.otpTtl, "resend_after_second": Constants.otpTtl,
    };
    return requestNormal(
      APIPaths.otpVerifyForDoingNextEvent,
      Method.POST,
      body,
      (data) => CreateOTPResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CampaignDetailResponseModel>> websitePageGetDetail(String id) async {
    final body = {"website_page_id": id};
    return requestNormal(
      APIPaths.websitePageGetDetail,
      Method.POST,
      body,
      (data) => CampaignDetailResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<CampaignDetailResponseModel>> websitePage(DetailPageRuleType rule) async {
    final body = {"code": rule.key};
    return requestNormal(
      APIPaths.websitePage,
      Method.GET,
      body,
      (data) => CampaignDetailResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<FAQItemModelResponse>> websiteFolderGetPageList() async {
    final body = {"folder_uri": "FAQ"};
    return requestNormal(
      APIPaths.websiteFolderGetPageList,
      Method.POST,
      body,
      (data) => FAQItemModelResponse.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> accountPasswordReset(String phone, String password) async {
    final body = {"login_name": phone, "password": password.toSha256()};
    return requestNormal(
      APIPaths.accountPasswordReset,
      Method.POST,
      body,
      (data) => EmptyCodable.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> accountPasswordChange(String phone, String password) async {
    String? token = await DataPreference.instance.token ?? "";
    final body = {"login_name": phone, "password": password.toSha256(), "access_token": token};
    return requestNormal(
      APIPaths.accountPasswordChange,
      Method.POST,
      body,
      (data) => EmptyCodable.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> accountLoginForPasswordChange(String phone, String password) async {
    String? token = await DataPreference.instance.token ?? "";
    final body = {"login_name": phone, "password": password.toSha256(), "access_token": token};
    return requestNormal(
      APIPaths.accountLoginForPasswordChange,
      Method.POST,
      body,
      (data) => EmptyCodable.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<BiometricRegisterResponseModel>> accountBioCredential() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {"deviceKey": deviceKey};
    return requestNormal(
      APIPaths.bioCredential,
      Method.POST,
      body,
      (data) => BiometricRegisterResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<BiometricRegisterResponseModel>> registerBiometric() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final body = {"deviceKey": deviceKey};
    return requestNormal(
      APIPaths.registerBiometric,
      Method.POST,
      body,
      (data) => BiometricRegisterResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<EmptyCodable>> unRegisterBiometric() async {
    var deviceKey = await DeviceInfo.getDeviceId();
    final path = "${APIPaths.unRegisterBiometric}/$deviceKey";
    final body = {"deviceKey": deviceKey};
    return requestNormal(path, Method.POST, body, (data) => EmptyCodable.fromJson(data as Json));
  }

  Future<BaseResponseModel<HeaderHomeModel>> getHomeHeaderData() async {
    return requestNormal(APIPaths.headerHome, Method.GET, {}, (data) => HeaderHomeModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<List<ProductModel>>> getProducts(Json body) async {
    return requestNormal(APIPaths.getProducts, Method.GET, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => ProductModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<SearchProductResponseModel>> getSearchProducts(Json body) async {
    return requestNormal(
      APIPaths.getSearchProducts,
      Method.POST,
      body,
      (data) => SearchProductResponseModel.fromJson(data as Json),
    );
  }

  Future<BaseResponseModel<ProductModel>> getProduct(int id) async {
    final path = APIPaths.getProductDetail.replaceAll("%@", id.toString());
    return requestNormal(path, Method.GET, {}, (data) => ProductModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<ProductModel>> getCustomerProductDetail(int id) async {
    final path = APIPaths.getCustomerProductDetail.replaceAll("%@", id.toString());
    return requestNormal(path, Method.GET, {}, (data) => ProductModel.fromJson(data as Json));
  }

  Future<BaseResponseModel<List<ProductStoreModel>>> getProductStores(int id) async {
    final body = {"product_id": id, "size": 20, "index": 0};
    return requestNormal(APIPaths.getProductStores, Method.GET, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => ProductStoreModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<LikeProductReponseModel>> likeProduct(int id) async {
    final body = {"product_id": id};
    return requestNormal(APIPaths.productCustomerLikes, Method.POST, body, (data) {
      return LikeProductReponseModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> unlikeProduct(int id) async {
    final path = APIPaths.productCustomerUnlikes.replaceAll("%@", id.toString());
    return requestNormal(path, Method.DELETE, {}, (data) => EmptyCodable.fromJson(data as Json));
  }

  Future<BaseResponseModel<GameBundleResponse>> getGames() async {
    return requestNormal(APIPaths.getGames, Method.GET, {}, (data) {
      return GameBundleResponse.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<EmptyCodable>>> verifyOrderProduct(Json body) async {
    return requestNormal(APIPaths.verifyOrderProduct, Method.POST, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => EmptyCodable.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<GameBundleItemModel>> getGameDetail(String id) async {
    final path = APIPaths.getGameDetail.replaceAll("%@", id);
    return requestNormal(path, Method.POST, {}, (data) {
      return GameBundleItemModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<AffiliateCategoryModel>>> affiliateCategoryGetList() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.affiliateCategoryGetList, Method.POST, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => AffiliateCategoryModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<List<AffiliateBrandModel>>> affiliateBrandGetList() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.affiliateBrandGetList, Method.POST, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => AffiliateBrandModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<List<AffiliateProductTopSaleModel>>> affiliateProductTopSale() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.affiliateProductTopSale, Method.POST, body, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => AffiliateProductTopSaleModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<CashbackOverviewModel>> getCashBackOverview() async {
    return requestNormal(APIPaths.getCashbackOverview, Method.GET, {}, (data) {
      return CashbackOverviewModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<RegistrationFormPackageModel>> getRegistrationForm(String id) async {
    final path = APIPaths.getRegistrationForm.replaceAll("%@", id);
    return requestNormal(path, Method.GET, {}, (data) {
      return RegistrationFormPackageModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<PreviewOrderPaymentModel>> getPreviewOrderInfo(Json body) async {
    return requestNormal(APIPaths.getPreviewOrderInfo, Method.POST, body, (data) {
      return PreviewOrderPaymentModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<List<PaymentBankAccountInfoModel>>> getPreviewOrderBankAccounts() async {
    return requestNormal(APIPaths.getPreviewOrderBankAccounts, Method.GET, {}, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => PaymentBankAccountInfoModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<List<PaymentMethodModel>>> getPreviewPaymentMethods() async {
    return requestNormal(APIPaths.getPreviewPaymentMethods, Method.GET, {}, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => PaymentMethodModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<List<CategoryNotifyItemModel>>> getNotificationCategories() async {
    return requestNormal(APIPaths.getNotificationCategories, Method.GET, {}, (data) {
      final list = data as List<dynamic>;
      return list.map((e) => CategoryNotifyItemModel.fromJson(e)).toList();
    });
  }

  Future<BaseResponseModel<NotificationListDataModel>> getNotifications(Json body) async {
    return requestNormal(APIPaths.getNotifications, Method.POST, body, (data) {
      return NotificationListDataModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> deleteNotification(String id) async {
    return requestNormal(APIPaths.deleteNotification, Method.POST, {"notification_id__": id}, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> deleteAllNotifications() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.deleteAllNotifications, Method.POST, body, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<EmptyCodable>> notificationMarkAsSeen() async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"access_token": token};
    return requestNormal(APIPaths.notificationMarkAsSeen, Method.POST, body, (data) {
      return EmptyCodable.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<NotificationDetailResponseModel>> getNotificationDetail(String id) async {
    String? token = DataPreference.instance.token ?? "";
    final body = {"notification_id": id, "mark_as_seen": "1", "access_token": token};
    return requestNormal(APIPaths.notificationGetDetail, Method.POST, body, (data) {
      return NotificationDetailResponseModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<TransactionHistoryModel>> getTransactionHistoryDetail(String id) async {
    final path = APIPaths.getTransactionHistoryDetail.replaceAll("%@", id);
    return requestNormal(path, Method.GET, {}, (data) {
      return TransactionHistoryModel.fromJson(data as Json);
    });
  }

  Future<BaseResponseModel<OrderProductPaymentResponseModel>> orderSubmitPayment({
    required List<ProductModel> products,
    required int quantity,
    required String requestId,
    int? point,
    int? cash,
    PaymentMethodModel? method,
    int? paymentTokenId,
    bool? saveToken,
    String? metadata,
  }) async {
    final items =
        products.map((product) {
          return {'product_id': product.id, 'product_type': product.type ?? '', 'quantity': quantity};
        }).toList();
    final Map<String, dynamic> params = {'request_id': requestId, 'items': items, 'flow': '21'};
    // flash_sale
    final firstProduct = products.first;
    if (firstProduct.previewFlashSale?.isFlashSalePrice == true && firstProduct.previewFlashSale?.id != null) {
      params['flash_sale_id'] = firstProduct.previewFlashSale!.id;
    }
    // Optional parameters
    if (method != null) {
      params['payment_method'] = method.code;
    }
    if (point != null && point != 0) {
      params['pay_point'] = point;
    }
    if (cash != null && cash != 0) {
      params['pay_cash'] = cash;
    }
    if (paymentTokenId != null) {
      params['payment_token_id'] = paymentTokenId;
    }
    if (saveToken != null) {
      params['save_token'] = saveToken;
    }
    if (metadata != null) {
      params['metadata'] = metadata;
    }
    return requestNormal(APIPaths.orderSubmitPayment, Method.POST, params, (data) {
      return OrderProductPaymentResponseModel.fromJson(data as Json);
    });
  }
}
