import 'dart:developer';

import 'dart:convert';

import 'package:dartz/dartz.dart';
import 'package:enaklo_pos/core/constants/variables.dart';
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
import 'package:enaklo_pos/data/models/response/order_remote_datasource.dart';
import 'package:enaklo_pos/data/models/response/payment_method_response_model.dart';
import 'package:enaklo_pos/data/models/response/summary_response_model.dart';
import 'package:enaklo_pos/presentation/home/models/order_model.dart';
import 'package:http/http.dart' as http;

class OrderRemoteDatasource {
  //save order to remote server
  Future<bool> saveOrder(OrderModel orderModel) async {
    final authData = await AuthLocalDataSource().getAuthData();
    print("🌐 API CALL: saveOrder");
    print("📡 URL: ${Variables.baseUrl}/api/save-order");
    print("🔑 Token: ${authData.token?.substring(0, 20)}...");
    try {
      final response = await http.post(
        Uri.parse('${Variables.baseUrl}/api/save-order'),
        body: orderModel.toJson(),
        headers: {
          'Authorization': 'Bearer ${authData.token}',
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      );
      
      print("📥 HTTP Status Code: ${response.statusCode}");
      print("📥 Response Body: ${response.body}");
      print("📥 Response Headers: ${response.headers}");
      
      if (response.statusCode == 200) {
        print("✅ API call successful - Order saved to server");
        return true;
      } else {
        print("❌ API call failed - Status: ${response.statusCode}");
        print("❌ Error Response: ${response.body}");
        return false;
      }
    } catch (e) {
      print("💥 API call error: $e");
      return false;
    }
  }

  Future<Either<String, OrderResponseModel>> getOrderByRangeDate(
    String stratDate,
    String endDate,
  ) async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final response = await http.get(
        Uri.parse(
            '${Variables.baseUrl}/api/orders?start_date=$stratDate&end_date=$endDate'),
        headers: {
          'Authorization': 'Bearer ${authData.token}',
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      );
      print("📥 HTTP Status Code: ${response.statusCode}");
      print("📥 Response Body: ${response.body}");
      print("📥 Response Headers: ${response.headers}");
      if (response.statusCode == 200) {
        print("✅ getOrderByRangeDate API call successful");
        return Right(OrderResponseModel.fromJson(response.body));
      } else {
        print("❌ getOrderByRangeDate API call failed - Status: ${response.statusCode}");
        print("❌ Error Response: ${response.body}");
        return const Left("Failed Load Data");
      }
    } catch (e) {
      print("💥 getOrderByRangeDate API call error: $e");
      return Left("Failed: $e");
    }
  }

  Future<Either<String, SummaryResponseModel>> getSummaryByRangeDate(
    String stratDate,
    String endDate,
  ) async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final response = await http.get(
        Uri.parse(
            '${Variables.baseUrl}/api/summary?start_date=$stratDate&end_date=$endDate'),
        headers: {
          'Authorization': 'Bearer ${authData.token}',
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      );
      print("📡 URL: ${response.request!.url}");
      print("📥 HTTP Status Code: ${response.statusCode}");
      print("📥 Response Body: ${response.body}");
      print("📥 Response Headers: ${response.headers}");
      if (response.statusCode == 200) {
        print("✅ getSummaryByRangeDate API call successful");
        return Right(SummaryResponseModel.fromJson(response.body));
      } else {
        print("❌ getSummaryByRangeDate API call failed - Status: ${response.statusCode}");
        print("❌ Error Response: ${response.body}");
        return const Left("Failed Load Data");
      }
    } catch (e) {
      print("💥 getSummaryByRangeDate API call error: $e");
      return Left("Failed: $e");
    }
  }

  Future<Either<String, PaymentMethodResponseModel>> getPaymentMethodByRangeDate(
    String startDate,
    String endDate,
  ) async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final response = await http.get(
        Uri.parse(
            '${Variables.baseUrl}/api/order-paymentmethod?start_date=$startDate&end_date=$endDate'),
        headers: {
          'Authorization': 'Bearer ${authData.token}',
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      );
      print("📥 Payment Method HTTP Status Code: ${response.statusCode}");
      print("📥 Payment Method Response Body: ${response.body}");
      print("📥 Payment Method Response Headers: ${response.headers}");
      if (response.statusCode == 200) {
        print("✅ getPaymentMethodByRangeDate API call successful");
        return Right(PaymentMethodResponseModel.fromJson(response.body));
      } else {
        print("❌ getPaymentMethodByRangeDate API call failed - Status: ${response.statusCode}");
        print("❌ Error Response: ${response.body}");
        return const Left("Failed Load Payment Method Data");
      }
    } catch (e) {
      print("💥 getPaymentMethodByRangeDate API call error: $e");
      return Left("Failed: $e");
    }
  }

  Future<Either<String, bool>> addOrderItems(
    int orderId,
    List<Map<String, dynamic>> orderItems,
  ) async {
    try {
      final authData = await AuthLocalDataSource().getAuthData();
      final response = await http.post(
        Uri.parse('${Variables.baseUrl}/api/orders/add-items'),
        headers: {
          'Authorization': 'Bearer ${authData.token}',
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'order_id': orderId,
          'order_items': orderItems,
        }),
      );
      
      print("📥 Add Order Items HTTP Status Code: ${response.statusCode}");
      print("📥 Add Order Items Response Body: ${response.body}");
      print("📥 Add Order Items Response Headers: ${response.headers}");
      
      if (response.statusCode == 200) {
        print("✅ addOrderItems API call successful");
        return const Right(true);
      } else {
        print("❌ addOrderItems API call failed - Status: ${response.statusCode}");
        print("❌ Error Response: ${response.body}");
        return Left("Failed to add order items: ${response.body}");
      }
    } catch (e) {
      print("💥 addOrderItems API call error: $e");
      return Left("Failed: $e");
    }
  }
}
