import 'dart:async';

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

import '../../print.dart';
import '../../views/home/map_page_passenger.dart';
import '../firebase/firbase_messge.dart';
import '../firebase/notification_service.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/otp/request.php',
        payload: {
          'receiver': phone,
          'context': 'token_change',
          'user_type': 'passenger',
          // '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/otp/verify.php',
        payload: {
          'phone_number': phone,
          'token_code': otpCode.value,
          'context': 'token_change',
          'user_type': 'passenger',
          'token': box.read(BoxName.tokenFCM).toString(),
          'fingerPrint': fingerPrint.toString(),
        },
      );

      if (response != 'failure' && response['status'] == 'success') {
        await NotificationService.sendNotification(
          category: 'token change',
          target: ptoken.toString(),
          title: 'token change'.tr,
          body: 'change device'.tr,
          isTopic: false, // Important: this is a token
          tone: 'cancel',
          driverList: [],
        );

        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;
    }
  }
}
