import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

import '../../../Helper/Logger.dart';
import '../../../constants/api_constants.dart';
import '../../../modules/orders/getcustomerorders.dart';
import '../../../modules/tenant/get_tenant.dart';
import '../../../service/dio.dart';

class CustomerTenantsProvider {
  final CustomDio customDio = CustomDio();

  Future<CustomerTenantsResponse?> getCustomerTenants(int customerId, int i) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    double? la = prefs.getDouble('lat');
    double? lo = prefs.getDouble('long');

    final url = "${ApiConstants.tenantCustomers}?customerid=$customerId&tenant=0&latitude=$la&longitude=$lo&categoryid=$i";
    logger.i("GET CustomerTenants URL: $url");

    CustomerTenantsResponse? responseModel;

    try {
      final response = await customDio.getData(url);

      if (response != null) {
        logger.i(response);
        responseModel = CustomerTenantsResponse.fromJson(response);
        logger.i("GET CustomerTenants Response: ${jsonEncode(responseModel.toJson())}");
      }
    } catch (e) {
      logger.e("Error in getCustomerTenants: $e");
    }

    return responseModel;
  }

  // Future<OrdersResponse?> getCustomerOrders(int customerId,  {required int pageNo, required int pageSize}) async {
  //
  //   print(pageNo);
  //   print(pageSize);
  //   print('ee');
  //   final url = "https://fiesta.nearle.app/live/api/v1/mob/orders/getcustomerorders/?customerid=$customerId&pageno=$pageNo&pagesize=$pageSize";
  //   logger.i("GET CustomerOrders URL: $url"); // Should now show pagesize=8
  //
  //   OrdersResponse? responseModel;
  //
  //   try {
  //     final response = await customDio.getData(url);
  //
  //     if (response != null) {
  //       responseModel = OrdersResponse.fromJson(response);
  //       logger.i("GET CustomerOrders Response: ${jsonEncode(responseModel.toJson())}");
  //     }
  //   } catch (e) {
  //     logger.e("Error in getCustomerOrders: $e");
  //   }
  //
  //   return responseModel;
  // }

  Future<OrdersResponse?> getCustomerOrders(
      int customerId, {
        required int pageNo,
        required int pageSize,
      }) async {
    print(pageNo);
    print(pageSize);
    print('ee');

    final url =
        "https://api.workolik.com/api/rest/getcustomerorders/?customerid=$customerId&pageno=$pageNo&pagesize=$pageSize";


    // final url =
    //     "${ApiConstants.getCustomerOrders}"
    //     "?customerid=$customerId"
    //     "&limit=$pageSize"
    //     "&offset=$pageNo";

    logger.i("GET CustomerOrders URL: $url");

    OrdersResponse? responseModel;

    try {
      final response = await customDio.getData(url);

      // 👇 Add this to see what actually came back
      logger.i("🔍 Raw response type: ${response.runtimeType}");
      logger.i("🔍 Raw response: $response");

      dynamic jsonResponse;

      if (response is String) {
        try {
          jsonResponse = jsonDecode(response);
        } catch (e) {
          logger.e("❌ JSON decode failed: $e");
          return null;
        }
      } else {
        jsonResponse = response;
      }

      if (jsonResponse != null && jsonResponse is Map<String, dynamic>) {
        responseModel = OrdersResponse.fromJson(jsonResponse);
        logger.i("✅ Parsed Orders Response: ${jsonEncode(responseModel.toJson())}");
      } else {
        logger.w("⚠️ Unexpected response format: $jsonResponse");
      }
    } catch (e) {
      logger.e("⛔ Error in getCustomerOrders: $e");
    }

    return responseModel;
  }


  Future<OrderResponse?> getCustomerOrderss(
      int customerId, {
        required int pageNo,
        required int pageSize,
      }) async {
    final offset = (pageNo - 1) * pageSize;

    final url =
        "https://api.workolik.com/api/rest/getcustomerorders"
        "?customerid=$customerId"
        "&tenantid=1087"
        "&moduleid=2"
        "&fromdate=2025-08-01T00:00:00"
        "&todate=2026-12-31T23:59:59"
        "&orderstatus=delivered"
        "&keyword=%%"
        "&limit=$pageSize"
        "&offset=$offset";

    try {
      logger.i("➡️ API Request: $url");

      final response = await customDio.getData(url, headers: {
        "x-hasura-admin-secret": "nearle-admin-secret",
        // OR
        // "x-hasura-access-key": "YOUR_ACCESS_KEY",
      },);

      logger.d("✅ API Response: $response");

      if (response != null) {
        return OrderResponse.fromJson(response);
      } else {
        logger.w("⚠️ API returned null");
        return null;
      }
    } catch (e, stackTrace) {
      logger.e("❌ API Error", error: e, stackTrace: stackTrace);
      return null;
    }
  }

  Future<Map<String, dynamic>?> createTenantCustomer({
    required int tenantId,
    required int locationId,
    required int customerId,
    required int status,
  }) async {
    final url = "https://fiesta.nearle.app/live/api/v1/mob/tenants/createtenantcustomer";
    final body = {
      "tenantid": tenantId,
      "locationid": locationId,
      "customerid": customerId,
      "status": status,
    };
    logger.i("POST CreateTenantCustomer URL: $url, Body: $body");

    try {
      final response = await customDio.postData(url, body);

      logger.i("POST CreateTenantCustomer Response: $response");

      // Ensure response is a Map<String, dynamic>
      if (response is Map<String, dynamic>) {
        return response;
      } else {
        // If API returned string or other type, wrap it
        return {'message': 'Something went wrong'};
      }
    } catch (e) {
      logger.e("Error in createTenantCustomer: $e");
      // Wrap exception in map
      return {'error':'Something went wrong'};
    }
  }

  Future<TenantLocationsResponse?> getTenantLocations(int tenantId) async {
    final url = "https://fiesta.nearle.app/live/api/v1/mob/tenants/gettenantlocations/?tenantid=$tenantId";
    logger.i("GET TenantLocations URL: $url");

    try {
      final response = await customDio.getData(url);

      if (response != null) {
        final responseModel = TenantLocationsResponse.fromJson(response);
        logger.i("GET TenantLocations Response: ${jsonEncode(responseModel.toJson())}");
        return responseModel; // <--- return the parsed modules
      }
    } catch (e) {
      logger.e("Error in getTenantLocations: $e");
    }

    return null; // <--- return null if request fails
  }







}
