import 'dart:async';

import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/links.dart';
import 'package:Intaleq/controller/functions/crud.dart';
import 'package:Intaleq/main.dart';
import 'package:get/get.dart';

import '../../print.dart';
import '../../views/home/map_page_passenger.dart';
import '../firebase/firbase_messge.dart';
import '../functions/package_info.dart';

class OtpVerificationController extends GetxController {
  final String phone;
  final String deviceToken;
  final String token;
  final otpCode = ''.obs;
  final isLoading = false.obs;
  final isVerifying = false.obs;
  var canResend = false.obs;
  var countdown = 120.obs;
  Timer? _timer;

  OtpVerificationController({
    required this.phone,
    required this.deviceToken,
    required this.token,
  });

  @override
  void onInit() {
    super.onInit();
    sendOtp(); // ترسل تلقائيًا عند فتح الصفحة
    startCountdown();
  }

  void startCountdown() {
    canResend.value = false;
    countdown.value = 120;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        canResend.value = true;
        timer.cancel();
      }
    });
  }

  Future<void> sendOtp() async {
    if (isLoading.value) return;
    isLoading.value = true;
    try {
      final response = await CRUD().post(
        link: '${AppLink.server}/auth/token_passenger/send_otp.php',
        payload: {
          'receiver': phone,
          // 'device_token': deviceToken,
        },
      );

      if (response != 'failure') {
        isLoading.value = true;
        // بإمكانك عرض رسالة نجاح هنا
      } else {
        Get.snackbar('Error'.tr, 'Failed to send OTP'.tr);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      // isLoading.value = false;
    }
  }

  Future<void> verifyOtp(String ptoken) async {
    isVerifying.value = true;

    try {
      String fingerPrint = await DeviceHelper.getDeviceFingerprint();
      final response = await CRUD().post(
        link: '${AppLink.server}/auth/token_passenger/verify_otp.php',
        payload: {
          'phone_number': phone,
          'otp': otpCode.value,
          'token': box.read(BoxName.tokenFCM).toString(),
          'fingerPrint': fingerPrint.toString(),
        },
      );

      if (response != 'failure' && response['status'] == 'success') {
        final fcm = Get.isRegistered<FirebaseMessagesController>()
            ? Get.find<FirebaseMessagesController>()
            : Get.put(FirebaseMessagesController());

        await fcm.sendNotificationToDriverMAP(
          'token change',
          'change device'.tr,
          ptoken.toString(),
          [],
          'cancel.wav',
        );
        await CRUD().post(
            link: "${AppLink.seferPaymentServer}/ride/firebase/add.php",
            payload: {
              'token': (box.read(BoxName.tokenFCM.toString())),
              'passengerID': box.read(BoxName.passengerID).toString(),
              "fingerPrint": fingerPrint.toString(),
            });
        // CRUD().post(
        //     link:
        //         '${AppLink.seferPaymentServer}/auth/token/update_passenger_token.php',
        //     payload: {
        //       'token': box.read(BoxName.tokenFCM).toString(),
        //       'fingerPrint': fingerPrint.toString(),
        //       'passengerID': box.read(BoxName.passengerID).toString(),
        //     });
        Get.offAll(() => const MapPagePassenger());
      } else {
        Get.snackbar('Verification Failed', 'OTP is incorrect or expired');
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      isVerifying.value = false;
    }
  }
}
