import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:gen_rentals/Models/CommonResponse.dart';
import 'package:gen_rentals/Models/HelpAndEnquiryModels/TicketChatDisplayResponse.dart';
import 'package:gen_rentals/Models/BillsModels/billListResponse.dart';
import 'package:gen_rentals/Models/ProfileResponse.dart';
import 'package:gen_rentals/Models/TransactionModels/PaymentReceiptDetailsResponse.dart';
import 'package:gen_rentals/Models/billProductResponse.dart';
import 'package:gen_rentals/Models/orderDetailsMainResponse.dart';
import 'package:gen_rentals/Models/orderDetailsProductResponse.dart';
import 'package:gen_rentals/Models/SubscribeOrderDetailsResponse.dart';
import 'package:gen_rentals/Models/HelpAndEnquiryModels/ticketListResponse.dart';
import '../Models/BillsModels/BillDetailsResponse.dart';
import '../Models/DashboardResponse.dart';
import '../Models/RentalPaymentDetailsResponse.dart';
import '../Models/TransactionModels/PayAmountResponse.dart';
import '../Models/TransactionModels/TransactionsResponse.dart';
import '../Models/orderDetailsBillResponse.dart';
import '../Models/rentalAccountResponse.dart';
import '../Models/rentalContactResponse.dart';
import '../Notifier/PayAmountProvider.dart';
import '../Notifier/RentalContactProvider .dart';
import 'api_URLs.dart';
import 'api_post_request.dart';
import 'package:http/http.dart' as http show MultipartFile;

class ApiCalling {


  /// Fetch rental contact by mobile number
  static Future<FetchMobileResponse?> fetchRentalMobileApi(
      String mob,
      ) async {
    debugPrint("############################### Api calling ");
    try {
      Map<String, String> data = {
        "mob": mob,
      };
      final res = await post(data, fetchMobileUrl, {});

      if (res != null) {
        return FetchMobileResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error: $e");
      return null;
    }
  }

  static Future<FetchMobileResponse?> fetchMobileOtpApi(
      String mob,
      String otp,
      deviceDetails
      ) async {
    debugPrint("############################### Api fetch otpcalling ");
    try {
      Map<String, String> data = {
        "mob": mob,
        "otp": otp,
        "device_details": deviceDetails.toString(),
      };
      print(data);
      final res = await post(data, fetchOtpUrl, {});
      if (res != null) {
        print(res);
        return FetchMobileResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error: $e");
      return null;
    }
  }

  static Future<CommonResponse?> logoutApi(
      String accId,
      String sessionId,
      ) async {
    debugPrint("############################### Api calling ");
    try {
      Map<String, String> data = {
        "acc_id": accId,
        "session_id": sessionId,
      };
      final res = await post(data, logoutUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ Logout API Error: $e");
      return null;
    }
  }


  /// pay_amount
  static Future<PayAmountResponse?> payAmountApi(
      String sessionId,
      String empId,
      String ammount,
      String refType,
      String refId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "acc_id": empId,
        "amount": ammount,
        "ref_type": refType,
        "ref_id": refId,
      };

      final res = await post(data, payAmountUrl, {});
      debugPrint("PayAmount Response ${res?.body}");

      if (res != null) {
        return PayAmountResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (payAmountApi): $e");
      return null;
    }
  }

  /// Fetch or get_payment_status
  static Future<PaymentStatusResponse?> getPaymentStatusApi(
      String sessionId,
      String empId,
      String razorpayOrderId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "emp_id": empId,
        "razorpay_order_id": razorpayOrderId,
      };

      final res = await post(data, getPaymentStatusUrl, {});

      if (res != null) {
        return PaymentStatusResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (razorpay_order_id): $e");
      return null;
    }
  }

  /// Fetch Bill List
  static Future<BillListResponse?> fetchBillListApi(
      String sessionId,
      String orderId,
      String accId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "order_id": orderId,
        "acc_id": accId,
      };

      final res = await post(data, billListUrl, {});

      if (res != null) {
        return BillListResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchBillList): $e");
      return null;
    }
  }

  /// Fetch Bill Details
  static Future<BillDetailsResponse?> fetchBillDetailsApi(
      String sessionId,
      String accId,
      String billId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "acc_id": accId,
        "bill_id": billId,
      };

      final res = await post(data, billDetailsUrl, {});

      debugPrint("Bill Details Response ${res?.body}");
      if (res != null) {
        return BillDetailsResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchBillDetails): $e");
      return null;
    }
  }


  ///  Bill Download api
  static Future<CommonResponse?> billDownloadApi(
      String sessionId,
      String empId,
      String accId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "bill_id": empId,
        "acc_id": accId,
      };

      final res = await post(data, downloadBillUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (billDownload): $e");
      return null;
    }
  }


  /// Payment Receipt Details api
  static Future<PaymentReceiptDetailsResponse?> fetchPaymentReceiptDetailsApi(
      String sessionId,
      String accId,
      String ledgerId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "acc_id": accId,
        "ledger_id": ledgerId,
      };

      final res = await post(data, paymentReceiptDetailsUrl, {});
      debugPrint("TR Response ${res?.body}");

      if (res != null) {
        return PaymentReceiptDetailsResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (paymentReceiptDetails): $e");
      return null;
    }
  }

  ///  Payment Receipt DownloadApi
  static Future<CommonResponse?> paymentReceiptDownloadApi(
      String sessionId,
      String ledgerId,
      String accId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "ledger_id": ledgerId,
        "acc_id": accId,
      };

      final res = await post(data, downloadReceiptUrl, {});
      debugPrint("DownloadApi Response${res}");

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (billDownload): $e");
      return null;
    }
  }


  /// Fetch Subscribe Order Details
  static Future<SubscribeOrderDetailsResponse?> fetchSubsOrderDetailApi(
      String sessionId,
      String orderId,
      String accId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "order_id": orderId,
        "acc_id": accId,
      };

      final res = await post(data, subsOrderDetails, {});
      debugPrint("Subscribe order details Response: ${res?.body}");

      if (res != null) {
        return SubscribeOrderDetailsResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchOrderList): $e");
      return null;
    }
  }




  /// Fetch Order Details Main
  static Future<OrderDetailsMainResponse?> fetchOrderDetailMainApi(
      String sessionId,
      String empId,
      String orderId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "emp_id": empId,
        "ord_id": orderId,
      };

      final res = await post(data, orderDetailsMainUrl, {});

      if (res != null) {
        return OrderDetailsMainResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchOrderDetailMain): $e");
      return null;
    }
  }

  /// Fetch Rental Transaction
  static Future<TransactionsResponse?> fetchRentalsTransactionsApi(
      String sessionId,
      String accId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "acc_id": accId,
      };

      final res = await post(data, transactionsUrl, {});

      if (res != null) {
        return TransactionsResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchRentalPaymentDetails): $e");
      return null;
    }
  }


  /// Fetch Ticket List
  static Future<TicketListResponse?> fetchTicketListApi(
      String sessionId,
      String accId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "acc_id": accId,
      };

      final res = await post(data, ticketListUrl, {});

      if (res != null) {
        return TicketListResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchTicketList): $e");
      return null;
    }
  }

  /// Fetch Ticket Chat Display
  static Future<TicketChatDisplayResponse?> fetchTicketChatDisplayApi(
      String sessionId,
      String accId,
      String ticketId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "acc_id": accId,
        "ticket_id": ticketId,
      };

      final res = await post(data, ticketChatDetailsUrl, {});
      // debugPrint("🟢 Raw API Response:\n${res?.body}");
      // debugPrint("🟢 Response Type: ${res?.body.runtimeType}");

      if (res != null) {
        return TicketChatDisplayResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchTicketChatDisplay): $e");
      return null;
    }
  }
  //
  // static Future<addTicketResponse?> addTicketAPI(
  //     type, description, List<http.MultipartFile> newList) async {
  //   if (await CheckHeaderValidity()) {
  //     try {
  //       Map<String, String> data = {
  //         'type': type.toString(),
  //         'description': description.toString(),
  //         //ticket_image
  //       };
  //       // print("Add ticket ${data}");
  //       final header = await HeaderValues();
  //       final res = await PostMultipleImagesNew(
  //           data, addTicketsUrl, header, newList);
  //       if (res != null) {
  //         return addTicketResponse.fromJson(jsonDecode(res));
  //       } else {
  //         return null;
  //       }
  //     } catch (e) {
  //       debugPrint('hello bev=bug $e ');
  //       return null;
  //     }
  //   } else {
  //     return addTicketResponse(error: "401");
  //   }
  // }


  /// Send Message Chat Api
  static Future<CommonResponse?> addMessageApi(
      String sessionId,
      String accId,
      String ticketId,
      String msgText,
      List<http.MultipartFile>? images,
      ) async {
    try {
      Map<String, String> body = {
        "session_id": sessionId,
        "acc_id": accId,
        "ticket_id": ticketId,
        "text": msgText,
      };

      Map<String, String> headers = {
        'Content-Type': 'multipart/form-data',
        // Add any other headers you need (auth tokens, etc.)
      };

      debugPrint("Data to addTicketApi${body}");

      final res = await PostMultipleImagesNew(
        body,
        addMessageUrl, // Your API endpoint
        headers,
        images ?? [], // Pass empty list if no images
      );
      debugPrint("Response from addMessageApi ${res}");
      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res));
      } else {
        debugPrint("Null Response from addMessageApi");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (addMessageApi): $e");
      return null;
    }
  }

  /// Create new ticket
  static Future<CommonResponse?> addTicketApi(
      String sessionId,
      String accId,
      String type,
      String description,
      String orderId,
      String otherReason,
      List<File>? images,
      ) async {

    try {
      Map<String, String> body = {
        "session_id": sessionId,
        "acc_id": accId,
        "type": type,
        "des": description,
        "order_id": orderId,
        "other_reason": otherReason,
      };

      Map<String, String> headers = {
        'Content-Type': 'multipart/form-data',
        // Add any other headers you need (auth tokens, etc.)
      };
      debugPrint("Data to addTicketApi${body}");

      final res = await postMessageWithImages(
        body,
        addTicketUrl, //  API endpoint
        headers,
        images ?? [], // Pass empty list if no images
      );
      debugPrint("Response from addTicketApi${res}");
      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res));
      } else {
        debugPrint("Null Response from addMessageApi");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (addMessageApi): $e");
      return null;
    }
  }



  /// Fetch Tag Order
  static Future<CommonResponse?> fetchTagOrderApi(
      String sessionId,
      String empId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "emp_id": empId,

      };

      final res = await post(data, tagOrderUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetchTagOrder): $e");
      return null;
    }
  }

  /// Submit Enquiry Api
  static Future<CommonResponse?> submitEnquiryApi(
      String sessionId,
      String accId,
      String name,
      String email,
      String mobile,
      String requirement,
      String note,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "acc_id": accId,
        "name": name,
        "email": email,
        "mob": mobile,
        "req": requirement,
        "note": note,

      };

      final res = await post(data, addEnquiryUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (enquiry Submit): $e");
      return null;
    }
  }

  /// Fetch CheckInOut Submit
  static Future<CommonResponse?> fetchCheckInOutSubmitApi(
      String sessionId,
      String empId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "emp_id": empId,

      };

      final res = await post(data, checkInOutSubmitUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (CheckInOutSubmit): $e");
      return null;
    }
  }

  /// Fetch Balance
  static Future<CommonResponse?> fetchBalanceApi(
      String sessionId,
      String empId,
      String accId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "emp_id": empId,
        "acc_id": accId,
      };

      final res = await post(data, balanceUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetch Balance): $e");
      return null;
    }
  }

  /// Add Payment
  static Future<CommonResponse?> fetchAddPaymentApi(
      String sessionId,
      String empId,
      String amount,
      String orderId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "emp_id": empId,
        "amount": amount,
        "order_id": orderId,
      };

      final res = await post(data, addPaymentUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (AddPaymentApi): $e");
      return null;
    }
  }


  /// Add Fcm Token
  static Future<CommonResponse?> fetchAddFcmTokenApi(
      String sessionId,
      String empId,
      String amount,
      String orderId,
      ) async {
    try {
      Map<String, String> data = {
        "session_id": sessionId,
        "emp_id": empId,
        "amount": amount,
        "order_id": orderId,
      };

      final res = await post(data, addFcmTokenUrl, {});

      if (res != null) {
        return CommonResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (fetch Add Payment Api): $e");
      return null;
    }
  }

  /// Fetch Dashboard
  static Future<DashboardResponse?> fetchDashboardApi(
      String accId,
      String sessionId,
      ) async {
    debugPrint("Dashboard Api called ##############");
    try {
      Map<String, String> data = {
        "acc_id": accId,
        "session_id": sessionId,
      };

      debugPrint("Account Id : $accId");

      final res = await post(data, dashboardUrl, {});
      debugPrint(res?.body);

      if (res != null) {
        return DashboardResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (Dashboard): $e");
      return null;
    }
  }

  /// Fetch Profile
  static Future<ProfileResponse?> fetchProfileApi(
      String accId,
      String sessionId,
      ) async {
    debugPrint("Profile Api called ##############");
    try {
      Map<String, String> data = {
        "acc_id": accId,
        "session_id": sessionId,
      };

      debugPrint("Account Id : $accId");

      final res = await post(data, profileDetailsUrl, {});
      debugPrint(res?.body);

      if (res != null) {
        return ProfileResponse.fromJson(jsonDecode(res.body));
      } else {
        debugPrint("Null Response");
        return null;
      }
    } catch (e) {
      debugPrint("❌ API Error (Profile): $e");
      return null;
    }
  }



}
