import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:get/get.dart';
import 'package:ride/constant/credential.dart';
import 'package:ride/controller/home/map_passenger_controller.dart';

import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../functions/crud.dart';

class PaymentController extends GetxController {
  bool isLoading = false;
  bool isWalletChecked = true;
  bool isCashChecked = false;
  bool isWalletFound = false;
  bool isPromoSheetDialogue = false;
  final formKey = GlobalKey<FormState>();
  final promo = TextEditingController();
  double totalPassenger = MapPassengerController().totalPassenger;
  int? selectedAmount = 0;
  List<dynamic> totalPassengerWalletDetails = [];
  String passengerTotalWalletAmount = '';
  void updateSelectedAmount(int value) {
    selectedAmount = value;
    update();
  }

  void changePromoSheetDialogue() {
    isPromoSheetDialogue = !isPromoSheetDialogue;
    update();
  }

  getPassengerWallet() async {
    isLoading = true;
    update();

    await CRUD().get(
        link: AppLink.getWalletByPassenger,
        payload: {'passenger_id': box.read(BoxName.passengerID)}).then((value) {
      box.write(BoxName.passengerWalletTotal,
          jsonDecode(value)['message'][0]['total'].toString());
    });

    isLoading = false;
    update();
  }

  void onChangedPaymentMethodWallet(bool? value) {
    isWalletChecked = !isWalletChecked;
    isWalletChecked ? isCashChecked = false : isCashChecked = true;
    update();
  }

  void onChangedPaymentMethodCash(bool? value) {
    isCashChecked = !isCashChecked;
    isCashChecked ? isWalletChecked = false : isWalletChecked = true;
    update();
  }

  void applyPromoCodeToPassenger() async {
    //TAWJIHI
    CRUD().get(link: AppLink.getPassengersPromo, payload: {
      'promo_code': promo.text,
    }).then((value) {
      var decod = jsonDecode(value);

      if (decod["status"] == "success") {
        print(totalPassenger);
        var firstElement = decod["message"][0];
        totalPassenger = totalPassenger -
            (totalPassenger * int.parse(firstElement['amount']));
        MapPassengerController().promoTaken = true;
        update();
        print(totalPassenger);
      }
    });
  }

  Future<void> makePayment(int amount, String currency) async {
    try {
      String clientSecret =
          await _getClientSecret((amount).toString(), currency);
      await initializePaymentSheet(clientSecret);
      await Stripe.instance.presentPaymentSheet();
    } catch (e) {
      throw Exception(e.toString());
    }
  }

  Future<void> initializePaymentSheet(String clientSecret) async {
    Stripe.instance.initPaymentSheet(
      paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: clientSecret,
        merchantDisplayName: 'Sefer',
      ),
    );
  }

  Future<String> _getClientSecret(String amount, currency) async {
    var res = await CRUD().postStripe(
      link: 'https://api.stripe.com/v1/payment_intents',
      payload: {'amount': amount, 'currency': currency},
    );
    final jsonResponse = jsonDecode(res);
    return jsonResponse['client_secret'];
  }

  @override
  void onInit() {
    getPassengerWallet();
    super.onInit();
  }
}
