import 'package:SEFER/constant/box_name.dart';
import 'package:dio/dio.dart' as dio;
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../constant/api_key.dart';
import '../../main.dart';

class PaymobManager extends GetxController {
  String authanticationToken1 = "";
  String orderId1 = "";

  Future<String> getPaymentKey(int amount, String currency) async {
    try {
      String authanticationToken = await _getAuthanticationToken();

      int orderId = await _getOrderId(
        authanticationToken: authanticationToken,
        amount: (100 * amount).toString(),
        currency: currency,
      );

      String paymentKey = await _getPaymentKey(
        authanticationToken: authanticationToken,
        amount: (100 * amount).toString(),
        currency: currency,
        orderId: orderId.toString(),
      );
      authanticationToken1 = authanticationToken.toString();
      orderId1 = orderId.toString();
      update();
      return paymentKey;
    } catch (e) {
      print("Exc==========================================");
      print(e.toString());
      throw Exception();
    }
  }

  Future<void> payWithPayMob(int amount, String currency) async {
    // 1. Fetch Payment Key (Assuming PaymobManager is a custom class)
    String paymentToken;
    try {
      paymentToken = await PaymobManager().getPaymentKey(amount, currency);
    } on Exception catch (e) {
      // Handle errors gracefully, e.g., display error message to user
      print("Error fetching payment key: $e");
      return;
    }

    // 2. Prepare Payment Data Payload
    final Map<String, dynamic> data = {
      "source": {
        "identifier": "01010101010", // Replace with actual source identifier
        "subtype": "WALLET",
      },
      "payment_token": paymentToken,
    };

    // 3. Make Payment Request using Dio
    final dio = Dio();
    try {
      final response = await dio.post(
        'https://accept.paymobsolutions.com/api/acceptance/payments/pay',
        data: data,
      );

      // 4. Handle Payment Response
      if (response.statusCode == 200) {
        final paymentData = response.data; // Assuming JSON response

        print("redirection_url: ${paymentData['iframe_redirection_url']}");

        // Navigate to success screen or display success message
        launchUrl(Uri.parse(paymentData['iframe_redirection_url']));
      } else {
        // Payment failed: Handle errors (e.g., display error message)
        print("Payment failed: ${response.statusCode} - ${response.data}");
      }
    } on DioError catch (e) {
      // Handle network or Dio-related errors
      print("Error making payment request: $e");
    }
  }

  Future<String> _getStatusAfterPaid() async {
    print(authanticationToken1);
    print(orderId1);
    final dio.Response response = await Dio().post(
        "https://accept.paymob.com/api/ecommerce/orders/transaction_inquiry",
        data: {
          "auth_token": authanticationToken1,
          "merchant_order_id": "970960",
          "order_id": orderId1
        });
    print(response.data);
    print(response.data['success']);
    return response.data["success"];
  }

  Future<String> _getAuthanticationToken() async {
    final dio.Response response =
        await Dio().post("https://accept.paymob.com/api/auth/tokens", data: {
      "api_key": AK.payMobApikey,
      'username': AK.usernamePayMob,
      "password": AK.passwordPayMob,
    });
    return response.data["token"];
  }

  Future<int> _getOrderId({
    required String authanticationToken,
    required String amount,
    required String currency,
  }) async {
    final dio.Response response = await Dio()
        .post("https://accept.paymob.com/api/ecommerce/orders", data: {
      "auth_token": authanticationToken,
      "amount_cents": amount,
      "currency": currency,
      "delivery_needed": "false",
      "items": [],
    });
    print('id is');
    print(response.data["id"]);
    return response.data["id"];
  }

  Future<String> _getPaymentKey({
    required String authanticationToken,
    required String orderId,
    required String amount,
    required String currency,
  }) async {
    final dio.Response response = await Dio()
        .post("https://accept.paymob.com/api/acceptance/payment_keys", data: {
      "expiration": 200,
      "auth_token": authanticationToken.toString(),
      "order_id": orderId.toString(),
      "integration_id":
          4556056, ////todo wallet or online card int.parse(AK.integrationIdPayMob),
      "lock_order_when_paid": "false",
      "amount_cents": amount,
      "currency": currency,
      "billing_data": {
        "first_name": box.read(BoxName.nameDriver) ?? box.read(BoxName.name),
        "last_name": box.read(BoxName.lastNameDriver) ?? box.read(BoxName.name),
        "email": box.read(BoxName.emailDriver) ?? box.read(BoxName.email),
        "phone_number":
            box.read(BoxName.phoneDriver) ?? box.read(BoxName.phone),
        "apartment": "NA",
        "floor": "NA",
        "street": "NA",
        "building": "NA",
        "shipping_method": "NA",
        "postal_code": "NA",
        "city": "NA",
        "country": box.read(BoxName.countryCode),
        "state": "NA"
      },
    });

    return response.data["token"];
  }
}
