import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../app.dart';

class OrderApi {
  static String className = 'OrderApi';

  static Future<List<OrderModel>> get(Map<String, dynamic> params) async {
    final String fnName = 'get';

    List<OrderModel> list = [];

    try {
      debugPrint('class: $className, method: $fnName, params $params');

      String path = Constants.BASE_URL + 'customer/orders';

      final response = await HttpUtil().get(path: path, queryParameters: params);

      for (final json in response['data']) {
        final OrderModel orderModel = OrderModel.fromJson(json);
        list.add(orderModel);
      }

      return list;
    } on DioError catch (error) {
      debugPrint('ERROR: class: $className, method: $fnName, error: $error ');

      int? errCode = error.response?.statusCode;

      if (errCode == 401) {
        Get.back();
      }
      return throw new Exception('Error occurred');
    } catch (e) {
      debugPrint('ERROR: class: $className, method: $fnName, error: $e ');
      throw new Exception('Error occurred');
    }
  }

  static Future<Map<String, dynamic>?> saveAddress(Map<String, dynamic> params) async {
    final String fnName = 'saveAddress';

    final Map<String, dynamic> map = {
      'shipping_rates': null,
      'payment_methods': null,
    };

    try {
      debugPrint('class: $className, method: $fnName, params: $params');

      String path = Constants.BASE_URL + 'customer/checkout/save-address';

      final response = await HttpUtil().post(path, data: jsonEncode(params));

      if (response['data']['shipping_rates'] != null) {
        final List<ShippingRateModel> list = [];
        for (var json in response['data']['shipping_rates']) {
          list.add(ShippingRateModel.fromJson(json));
        }

        map['shipping_rates'] = list;
      }

      if (response['data']['payment_methods'] != null) {
        final List<PaymentMethodModel> list = [];
        for (final json in response['data']['payment_methods']) {
          list.add(PaymentMethodModel.fromJson(json));
        }

        map['payment_methods'] = list;
      }

      return map;
    } on DioError catch (error) {
      debugPrint('ERROR: class: $className, method: $fnName, error: $error ');

      int? errCode = error.response?.statusCode;

      if (errCode == 401) {
        Get.offNamedUntil('/', (route) => false);
        navigateToLoginScreen();

        showSnack('warning'.tr, 'please_login'.tr, SnackType.WARNING);
      }
      return null;
    } catch (e) {
      debugPrint('ERROR: class: $className, method: $fnName, params: $params, error: $e ');
      // throw new Exception('Error occurred');
      return null;
    }
  }

  static Future<Map<String, dynamic>> saveOrder(Map<String, dynamic> params) async {
    final String fnName = 'saveOrder';

    try {
      debugPrint('class: $className, method: $fnName, params: $params');

      String path = Constants.BASE_URL + 'customer/checkout/save-order';

      final response = await HttpUtil().post(path, queryParameters: params);

      debugPrint('response $fnName, $response');

      if (!response['success']) showSnack('error'.tr, 'error_occurred'.tr, SnackType.ERROR);

      return {'success': response['success'], 'url': response['url'] ?? ''};
    } on DioError catch (error) {
      debugPrint('ERROR: class: $className, method: $fnName, error: $error ');

      int? errCode = error.response?.statusCode;

      if (errCode == 401) {
        Get.offNamedUntil('/', (route) => false);
        navigateToLoginScreen();
        showSnack('warning'.tr, 'please_login'.tr, SnackType.WARNING);
      }
      return {'success': false, 'url': ''};
    } catch (e) {
      debugPrint('ERROR: class: $className, method: $fnName, params: $params, error: $e ');
      showSnack('error'.tr, 'error_occurred'.tr, SnackType.ERROR);
      return {'success': false, 'url': ''};
    }
  }

  static Future<bool> cancelOrder(int orderId) async {
    final String fnName = 'cancel';

    try {
      debugPrint('class: $className, method: $fnName');

      String path = Constants.BASE_URL + 'customer/orders/$orderId/cancel';

      await HttpUtil().post(path);

      return true;
    } catch (e) {
      debugPrint('ERROR: class: $className, method: $fnName, error: $e ');
      return false;
    }
  }

  static Future<CartModel?> saveShipping(Map<String, dynamic> params) async {
    final String fnName = 'saveShipping';

    try {
      debugPrint('class: $className, method: $fnName, params: $params');

      String path = Constants.BASE_URL + 'customer/checkout/save_shipping';

      final response = await HttpUtil().post(path, queryParameters: params);

      return CartModel.fromJson(response['data']['cart']);
    } on DioError catch (error) {
      debugPrint('ERROR: class: $className, method: $fnName, error: $error ');

      int? errCode = error.response?.statusCode;

      if (errCode == 401) {
        Get.offNamedUntil('/', (route) => false);
        navigateToLoginScreen();
        showSnack('warning'.tr, 'please_login'.tr, SnackType.WARNING);
      }
      return null;
    } catch (e) {
      debugPrint('ERROR: class: $className, method: $fnName, params: $params, error: $e ');
      showSnack('error'.tr, 'error_occurred'.tr, SnackType.ERROR);
      return null;
    }
  }

}
