import 'dart:async';

import 'package:get/get.dart';
import 'package:sefer_driver/print.dart';
import 'package:sefer_driver/views/home/Captin/home_captain/home_captin.dart';

import '../../../constant/box_name.dart';
import '../../../constant/links.dart';
import '../../../main.dart';
import '../../../views/widgets/error_snakbar.dart';
import '../../firebase/firbase_messge.dart';
import '../../firebase/notification_service.dart';
import '../../functions/crud.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 {
    isLoading.value = true;
    try {
      final response = await CRUD().post(
        link:
            '${AppLink.server}/auth/token_passenger/driver/send_otp_driver.php',
        payload: {
          'receiver': phone,
          // 'device_token': deviceToken,
        },
      );

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

  Future<void> verifyOtp(String ptoken) async {
    isVerifying.value = true;
    var finger = box.read(BoxName.deviceFingerprint);
    try {
      final response = await CRUD().post(
        link:
            '${AppLink.server}/auth/token_passenger/driver/verify_otp_driver.php',
        payload: {
          'phone_number': phone,
          'otp': otpCode.value,
          'token': box.read(BoxName.tokenDriver).toString(),
          'fingerPrint': finger.toString(),
        },
      );

      if (response != 'failure' &&
          response != 'token_expired' &&
          response != 'no_internet') {
        Log.print('response (already decoded): ${response}');

        // توجه إلى الصفحة التالية
        await CRUD().post(
            link: '${AppLink.paymentServer}/auth/token/update_driver_auth.php',
            payload: {
              'token': box.read(BoxName.tokenDriver).toString(),
              'fingerPrint': finger.toString(),
              'captain_id': box.read(BoxName.driverID).toString(),
            });

        await NotificationService.sendNotification(
          target: ptoken.toString(),
          title: 'token change'.tr,
          body: 'token change'.tr,
          isTopic: false,
          tone: 'cancel',
          driverList: [],
          category: 'token change',
        );

        Get.offAll(() => HomeCaptain());
      } else {
        mySnackeBarError('OTP is incorrect or expired'.tr);
      }
    } catch (e) {
      mySnackeBarError(e.toString());
    } finally {
      isVerifying.value = false;
    }
  }
}
