import 'dart:convert';

import 'package:local_auth/local_auth.dart';
import 'package:sefer_driver/constant/style.dart';
import 'package:sefer_driver/controller/firebase/firbase_messge.dart';
import 'package:sefer_driver/controller/firebase/local_notification.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';

import '../../../views/widgets/mydialoug.dart';
import '../../firebase/notification_service.dart';

class CaptainWalletController extends GetxController {
  bool isLoading = false;
  final formKeyTransfer = GlobalKey<FormState>();
  final formKeyAccount = GlobalKey<FormState>();
  Map walletDate = {};
  Map walletDateVisa = {};
  Map walletDriverPointsDate = {};
  final formKey = GlobalKey<FormState>();
  String totalAmount = '0';
  double kazan = 0;
  String totalAmountVisa = '0';
  String totalPoints = '0';
  final amountFromBudgetController = TextEditingController();
  final newDriverPhoneController = TextEditingController();
  final phoneWallet = TextEditingController();
  final cardBank = TextEditingController();
  final bankCode = TextEditingController();

  payFromBudget() async {
    if (formKey.currentState!.validate()) {
      var pointFromBudget = int.parse((amountFromBudgetController.text));

      // await getPaymentId('fromBudgetToPoints',
      //     int.parse((amountFromBudgetController.text)) * -1);
      var paymentToken3 =
          await generateToken((pointFromBudget * -1).toString());
      var paymentID = await getPaymentId(
          'fromBudgetToPoints', (pointFromBudget * -1).toString());
      await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
        'amount': (pointFromBudget * -1).toString(),
        'rideId': paymentID.toString(),
        'payment_method': 'myBudget',
        'passengerID': 'myBudgetToPoint',
        'token': paymentToken3,
        'driverID': box.read(BoxName.driverID).toString(),
      });
      Future.delayed(const Duration(seconds: 1));
      await addDriverWallet(
          'fromBudget', pointFromBudget.toString(), pointFromBudget.toString());
      update();
      Get.back();
      await refreshCaptainWallet();
      NotificationController().showNotification(
        'You have successfully charged your account'.tr,
        '$pointFromBudget ${'has been added to your budget'.tr}',
        'tone1',
        '',
      );
    }
  }

  Future refreshCaptainWallet() async {
    await getCaptainWalletFromRide();
    await getCaptainWalletFromBuyPoints();
    // await checkAccountCaptainBank();
  }

  List amountToNewDriverMap = [];
  bool isNewTransfer = false;
  Future detectNewDriverFromMyBudget() async {
    if (formKeyTransfer.currentState!.validate()) {
      if (int.parse(amountFromBudgetController.text) <
              double.parse(totalAmountVisa) &&
          int.parse(amountFromBudgetController.text) > 10) {
        //get new driver details
        isNewTransfer = true;
        update();
        var res = await CRUD().get(
            link: AppLink.getDriverDetails,
            payload: {'driver_phone': '+2${newDriverPhoneController.text}'});
        isNewTransfer = false;
        update();
        if (res != 'failure') {
          var d = jsonDecode(res);
          amountToNewDriverMap = d['data'];
          // update();
        } else {
          mySnackeBarError("This driver is not registered".tr);
        }
      } else {
        mySnackeBarError('Your Budget less than needed'.tr);
      }
    }
  }

  Future getCaptainWalletFromRide() async {
    isLoading = true;
    update();
    var res = await CRUD().getWallet(
      link: AppLink.getAllPaymentFromRide,
      payload: {'driverID': box.read(BoxName.driverID).toString()},
    );
    // isLoading = false;
    if (res != 'failure') {
      walletDate = jsonDecode(res);
      totalAmount = walletDate['message'][0]['total_amount'] ?? '0';
      update();
      var res1 = await CRUD().getWallet(
          link: AppLink.getAllPaymentVisa,
          payload: {'driverID': box.read(BoxName.driverID).toString()});
      walletDateVisa = jsonDecode(res1);
      totalAmountVisa = walletDateVisa['message'][0]['diff'].toString();

      update();
    } else {
      totalAmount = "0";
      totalAmountVisa = "0";
    }
  }

  Future getCaptainWalletFromBuyPoints() async {
    // isLoading = true;
    update();

    var res = await CRUD().getWallet(
      link: AppLink.getDriverPaymentPoints,
      payload: {'driverID': box.read(BoxName.driverID).toString()},
    );
    isLoading = false;
    // update();

    if (res != 'failure') {
      walletDriverPointsDate = jsonDecode(res);
      double totalPointsDouble = double.parse(
          walletDriverPointsDate['message'][0]['total_amount'].toString());
      totalPoints = totalPointsDouble.toStringAsFixed(0);
    } else {
      totalPoints = '0';
    }

    update();
  }

  String paymentToken = '';
  Future<String> generateToken(String amount) async {
    var res =
        await CRUD().postWallet(link: AppLink.addPaymentTokenDriver, payload: {
      'driverID': box.read(BoxName.driverID).toString(),
      'amount': amount.toString(),
    });
    var d = (res);
    return d['message'];
  }

  // late String paymentID;
  Future<String> getPaymentId(String paymentMethod, amount) async {
    // paymentToken = await generateToken(amount);
    var res =
        await CRUD().postWallet(link: AppLink.addDriverPaymentPoints, payload: {
      'driverID': box.read(BoxName.driverID).toString(),
      'amount': amount.toString(),
      'payment_method': paymentMethod.toString(),
    });
    var d = (res);
    // paymentID = d['message'].toString();
    return d['message'];
  }

  Future addDriverWallet(String paymentMethod, point, count) async {
    paymentToken = await generateToken(count);
    var paymentID = await getPaymentId(paymentMethod, point.toString());
    await CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
      'driverID': box.read(BoxName.driverID).toString(),
      'paymentID': paymentID.toString(),
      'amount': point,
      'token': paymentToken,
      'paymentMethod': paymentMethod.toString(),
    });
  }

  Future addDriverPayment(String paymentMethod, point, wayPay) async {
    paymentToken = await generateToken(point);
    var paymentID = await getPaymentId(paymentMethod, point.toString());
    await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
      'amount': point.toString(),
      'rideId': paymentID.toString(),
      'payment_method': paymentMethod,
      'passengerID': wayPay,
      'token': paymentToken,
      'driverID': box.read(BoxName.driverID).toString(),
    });
  }

  Future addDriverWalletFromPromo(String paymentMethod, point) async {
    var resPromotion =
        await CRUD().postWallet(link: AppLink.addpromotionDriver, payload: {
      'driver_id': box.read(BoxName.driverID).toString(),
      'payment_amount': point,
      'timePromo': paymentMethod,
    });
    if (resPromotion != 'failure') {
      paymentToken = await generateToken(point);
      var paymentID = await getPaymentId(paymentMethod, point.toString());
      var res =
          await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
        'amount': point,
        'rideId': paymentID.toString(),
        'payment_method': paymentMethod.toString(),
        'passengerID': paymentMethod,
        'token': paymentToken,
        'driverID': box.read(BoxName.driverID).toString(),
      });
      if (res != 'failure') {
        String title = 'wallet_updated'.tr; // Notification title
        String message = '${'wallet_credited_message'.tr} $point';
        String tone = 'default_tone'.tr; // Notification tone or sound
        String payLoad =
            'wallet_updated'; // Additional data payload for the notification

        Get.find<NotificationController>()
            .showNotification(title, message, tone, payLoad);
      }
    } else {
      Get.back();
      mySnackeBarError(
          "A promotion record for this driver already exists for today.".tr);
    }
  }

  Future addDriverWalletToInvitor(String paymentMethod, driverID, point) async {
    paymentToken = await generateToken(point);
    var paymentID = await getPaymentId(paymentMethod, point.toString());
    await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
      'driverID': driverID,
      'amount': point,
      'token': paymentToken,
      'rideId': paymentID.toString(),
      'payment_method': paymentMethod.toString(),
      'passengerID': paymentMethod,
    });
    await addSeferWallet(paymentMethod,
        (double.parse(point) * -2).toString()); // deduct 2 from sefer wallet
  }

  Future addSeferWallet(String paymentMethod, String point) async {
    var seferToken = await generateToken(point.toString());
    await CRUD().postWallet(link: AppLink.addSeferWallet, payload: {
      'amount': point.toString(),
      'paymentMethod': paymentMethod,
      'passengerId': 'driver',
      'token': seferToken,
      'driverId': box.read(BoxName.driverID).toString(),
    });
  }

  Future addTransferDriversWallet(String paymentMethod1, paymentMethod2) async {
    var paymentID =
        await getPaymentId(paymentMethod1, amountFromBudgetController.text);
    paymentToken = await generateToken(
        (int.parse(amountFromBudgetController.text) * -1).toString());

    await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
      'amount': (int.parse(amountFromBudgetController.text) * -1).toString(),
      'rideId': paymentID.toString(),
      'payment_method': paymentMethod1,
      'passengerID': 'To ${amountToNewDriverMap[0]['id']}',
      'token': paymentToken,
      'driverID': box.read(BoxName.driverID).toString(),
    });

    paymentID = await getPaymentId(paymentMethod2,
        (int.parse(amountFromBudgetController.text) - 5).toString());
    paymentToken = await generateToken(amountFromBudgetController.text);
    var res1 =
        await CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
      'driverID': amountToNewDriverMap[0]['id'].toString(),
      'paymentID': paymentID.toString(),
      'amount': ((int.parse(amountFromBudgetController.text) - 5))
          // kazan) // double.parse(kazan) .08 for egypt
          .toStringAsFixed(
              0), // this will convert buddget to poitns by kazan .08

      'token': paymentToken,
      'paymentMethod': paymentMethod2.toString(),
    });
    if (res1 != 'failure') {
      // Get.find<FirebaseMessagesController>().sendNotificationToDriverMAP(
      //     'Transfer',
      //     '${'You have transfer to your wallet from'.tr}'
      //         '${box.read(BoxName.nameDriver)}',
      //     amountToNewDriverMap[0]['token'].toString(),
      //     [],
      //     'order1.wav');
      NotificationService.sendNotification(
        target: amountToNewDriverMap[0]['token'].toString(),
        title: 'Transfer'.tr,
        body: '${'You have transfer to your wallet from'.tr}'
            '${box.read(BoxName.nameDriver)}',

        isTopic: false, // Important: this is a token
        tone: 'ding',
        driverList: [], category: 'Transfer',
      );
      await addSeferWallet('payout fee', '5');

      Get.defaultDialog(
          title: 'transfer Successful'.tr,
          middleText: '',
          titleStyle: AppStyle.title,
          confirm: MyElevatedButton(
              title: 'Ok'.tr,
              onPressed: () async {
                Get.back();
                Get.back();

                await refreshCaptainWallet();
              }));
    }
  }

  //check if account bank is created or not
  Future checkAccountCaptainBank() async {
    isLoading = true;
    update();
    if (box.read(BoxName.accountIdStripeConnect).toString().isEmpty) {
      var res = await CRUD().get(link: AppLink.getAccount, payload: {
        'id': box.read(BoxName.driverID).toString(),
      });
      var d = jsonDecode(res);
      if (d['status'] != 'failure') {
        box.write(BoxName.accountIdStripeConnect,
            d['message'][0]['accountBank'].toString());
      }
    }
    isLoading = false;
    update();
  }

  getKazanPercent() async {
    var res = await CRUD().get(
      link: AppLink.getKazanPercent,
      payload: {'country': box.read(BoxName.countryCode).toString()},
    );
    if (res != 'failure') {
      var json = jsonDecode(res);
      kazan = double.parse(json['message'][0]['kazan'].toString());
      // naturePrice = double.parse(json['message'][0]['naturePrice']);
      // heavyPrice = double.parse(json['message'][0]['heavyPrice']);
      // latePrice = double.parse(json['message'][0]['latePrice']);
      // comfortPrice = double.parse(json['message'][0]['comfortPrice']);
      // speedPrice = double.parse(json['message'][0]['speedPrice']);
      // deliveryPrice = double.parse(json['message'][0]['deliveryPrice']);
      // mashwariPrice = double.parse(json['message'][0]['freePrice']);
      // fuelPrice = double.parse(json['message'][0]['fuelPrice']);
    }
    update();
  }

  @override
  void onInit() async {
    // getKazanPercent();

    await refreshCaptainWallet();
    super.onInit();
  }
}
