import 'package:sefer_driver/controller/firebase/firbase_messge.dart';
import 'package:sefer_driver/controller/home/captin/map_driver_controller.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:flutter/cupertino.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/constant/style.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/home/Captin/home_captain/home_captin.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';

import '../firebase/notification_service.dart';
import '../home/captin/home_captain_controller.dart';

// import '../home/captin/home_captain_controller.dart';

class RateController extends GetxController {
  double selectedRateItemId = -1;
  TextEditingController comment = TextEditingController();
  TextEditingController passengerPayAmount = TextEditingController();
  String? rideId, passengerId, driverId, price;
  late GlobalKey<FormState> formKey;
  bool ispassengerWantWalletFromDriver = false;
  String walletChecked = '';
  @override
  void onInit() {
    formKey = GlobalKey<FormState>();
    passengerId = Get.arguments['passengerId'];
    rideId = Get.arguments['rideId'];
    driverId = Get.arguments['driverId'];
    price = Get.arguments['price'];
    walletChecked = Get.arguments['walletChecked'];
    super.onInit();
  }

  void passengerWantPay() {
    ispassengerWantWalletFromDriver = true;
    update();
  }

  Future addPassengerWallet() async {
    if (formKey.currentState!.validate()) {
      var priceOfTrip = double.parse(price.toString());
      // double.parse(Get.find<MapDriverController>().paymentAmount);
      double remainingFee = double.parse(passengerPayAmount.text) - priceOfTrip;
      if (remainingFee > 0) {
        var paymentToken2 = await Get.find<MapDriverController>()
            .generateTokenPassenger(remainingFee.toString());
        await CRUD().post(link: AppLink.addPassengersWallet, payload: {
          'passenger_id': passengerId,
          'balance': remainingFee.toString(),
          'token': paymentToken2,
        }).then((value) async {
          if (value != 'failure') {
            mySnackbarSuccess('Wallet Added'.tr);
            // if (double.parse(
            //         Get.find<CaptainWalletController>().totalAmountVisa) >
            //     remainingFee) {
            var paymentToken3 = await Get.find<MapDriverController>()
                .generateTokenDriver((-1 * remainingFee).toString());

            await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
              'rideId': 'remain$rideId',
              'amount': (-1 * remainingFee).toString(),
              'payment_method': 'Remainder',
              'passengerID': passengerId,
              'token': paymentToken3,
              'driverID': box.read(BoxName.driverID).toString(),
            });
            NotificationService.sendNotification(
              target: Get.find<MapDriverController>().tokenPassenger.toString(),
              title: 'Wallet Added'.tr,
              body: 'Wallet Added${(remainingFee).toStringAsFixed(0)}'.tr,
              isTopic: false, // Important: this is a token
              tone: 'tone2',
              driverList: [], category: 'Wallet Added',
            );
            walletChecked = 'true';
            // }

            update();
          }
        });
      } else {
        Get.defaultDialog(
            title: '${'The price must be over than '.tr} $priceOfTrip',
            middleText: '',
            confirm: MyElevatedButton(
                title: 'Ok'.tr,
                onPressed: () {
                  Get.back();
                }));
      }
    }
  }

  void selectRateItem(double id) {
    selectedRateItemId = id;
    update();
  }

  void addRateToPassenger() async {
    // HomeCaptainController homeCaptainController =
    //     Get.find<HomeCaptainController>();
    // Get.put(MapDriverController());
    if (selectedRateItemId < 1) {
      Get.defaultDialog(
          title: 'You Should choose rate figure'.tr,
          titleStyle: AppStyle.title,
          middleText: '',
          confirm: MyElevatedButton(title: 'Ok', onPressed: () => Get.back()));
    } else {
      await CRUD().post(link: "${AppLink.server}/ride/rate/add.php", payload: {
        'passenger_id': passengerId,
        'driverID': box.read(BoxName.driverID).toString(),
        'rideId': rideId.toString(),
        'rating': selectedRateItemId.toString(),
        'comment': comment.text ?? 'none',
      });

      CRUD().sendEmail(AppLink.sendEmailToPassengerForTripDetails, {
        'startLocation':
            Get.find<MapDriverController>().passengerLocation.toString(),
        'endLocation':
            Get.find<MapDriverController>().passengerDestination.toString(),
        'name': Get.find<MapDriverController>().passengerName.toString(),
        'timeOfTrip': Get.find<MapDriverController>().timeOfOrder.toString(),
        'fee': Get.find<MapDriverController>().totalPricePassenger.toString(),
        'duration': Get.find<MapDriverController>().duration.toString(),
        'phone': Get.find<MapDriverController>().passengerPhone.toString(),
        'email': Get.find<MapDriverController>().passengerEmail.toString(),
        'startNameLocation':
            Get.find<MapDriverController>().startNameLocation.toString(),
        'endNameLocation':
            Get.find<MapDriverController>().endNameLocation.toString(),
      });
      if (Get.isRegistered<MapDriverController>()) {
        Get.find<MapDriverController>()
            .disposeEverything(); // الدالة التي أنشأناها في الخطوة 3
        Get.delete<MapDriverController>(force: true); // حذف إجباري من الذاكرة
      }
      Get.offAll(HomeCaptain());
      if (Get.isRegistered<HomeCaptainController>()) {
        Get.find<HomeCaptainController>().resumeHomeMapUpdates();
      }
    }
  }
}
