import 'package:siro_rider/constant/links.dart';
import 'package:get/get.dart';
import '../../../constant/box_name.dart';
import '../../../main.dart';
import '../../../print.dart';
import '../../views/auth/otp_page.dart';
import '../../views/widgets/error_snakbar.dart';
import '../functions/crud.dart';
import '../functions/package_info.dart';
import '../functions/country_logic.dart';
import 'login_controller.dart';

// --- Helper Class for Phone Authentication ---

class PhoneAuthHelper {
  // Define your server URLs
  static final String _sendOtpUrl = '${AppLink.server}/auth/otp/request.php';
  static final String _verifyOtpUrl = '${AppLink.server}/auth/otp/verify.php';
  static final String _registerUrl = '${AppLink.server}/auth/syria/register_passenger.php';

  // removed formatSyrianPhone

  /// Sends an OTP to the provided phone number.
  static Future<bool> sendOtp(String phoneNumber) async {
    try {
      // إصلاح الرقم قبل الإرسال
      final fixedPhone = CountryLogic.formatCurrentCountryPhone(phoneNumber);

      final response = await CRUD().post(
        link: _sendOtpUrl,
        payload: {
          'receiver': fixedPhone,
          'context': 'login',
          'user_type': 'passenger'
        },
      );

      if (response != 'failure') {
        final data = response;

        if (data['status'] == 'success') {
          mySnackbarSuccess('An OTP has been sent to your number.'.tr);
          return true;
        } else {
          mySnackeBarError(data['message'] ?? 'Failed to send OTP.');
          return false;
        }
      } else {
        mySnackeBarError('Server error. Please try again.'.tr);
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  /// Verifies the OTP and logs the user in.

  static Future<void> verifyOtp(String phoneNumber, String otpCode) async {
    try {
      final fixedPhone = CountryLogic.formatCurrentCountryPhone(phoneNumber);
      final response = await CRUD().post(
        link: _verifyOtpUrl,
        payload: {
          'phone_number': fixedPhone,
          'token_code': otpCode,
          'context': 'login',
          'user_type': 'passenger'
        },
      );

      if (response != 'failure') {
        final data = (response);
        Log.print('data: ${data}');

        if (data['status'] == 'success') {
          final isRegistered = data['message']['isRegistered'] ?? false;
          Log.print('isRegistered: ${isRegistered}');

          if (isRegistered) {
            // ✅ المستخدم موجود مسبقاً -> تسجيل دخول مباشر
            await _handleSuccessfulLogin(data['message']['passenger']);
          } else {
            // ✅ مستخدم جديد -> الذهاب لصفحة التسجيل
            mySnackbarSuccess(
                'Phone verified. Please complete registration.'.tr);
            Get.to(() => RegistrationScreen(phoneNumber: phoneNumber));
          }
        } else {
          mySnackeBarError(data['message']);
        }
      } else {
        mySnackeBarError('Server error. Please try again.'.tr);
      }
    } catch (e) {
      mySnackeBarError('An error occurred: $e');
    }
  }

  static Future<void> _addTokens() async {
    String fingerPrint = await DeviceHelper.getDeviceFingerprint();

    var res = await CRUD()
        // this for register and login //
        .post(link: "${AppLink.server}/ride/firebase/addToken.php", payload: {
      'token': (box.read(BoxName.tokenFCM.toString())),
      'passengerID': box.read(BoxName.passengerID).toString(),
      "fingerPrint": fingerPrint
    });
    Log.print('res token: ${res}');
  }

  static Future<void> registerUser({
    required String phoneNumber,
    required String firstName,
    required String lastName,
    String? email,
  }) async {
    try {
      final fixedPhone = CountryLogic.formatCurrentCountryPhone(phoneNumber);
      final response = await CRUD().post(
        link: _registerUrl,
        payload: {
          'phone_number': fixedPhone,
          'first_name': firstName,
          'last_name': lastName,
          'email': email ?? '', // Send empty string if null
        },
      );
      final data = (response);
      if (data != 'failure') {
        // Registration successful, log user in

        await _handleSuccessfulLogin(data['message']['data']);
      } else {
        mySnackeBarError(
            "User with this phone number or email already exists.".tr);
      }
    } catch (e) {
      Log.print('e: ${e}');
      mySnackeBarError('An error occurred: $e');
    }
  }

  static Future<void> _handleSuccessfulLogin(
      Map<String, dynamic> userData) async {
    mySnackbarSuccess('Welcome, ${userData['first_name']}!');

    // Save user data to local storage (Hive box) using new keys
    box.write(BoxName.passengerID, userData['id']);
    box.write(BoxName.name, userData['first_name']);
    box.write(BoxName.lastName, userData['last_name']);
    box.write(BoxName.email, userData['email']);
    box.write(BoxName.phone, userData['phone']);
    box.write(BoxName.isVerified, '1');
    await _addTokens();
    await Get.put(LoginController()).loginUsingCredentials(
      box.read(BoxName.passengerID).toString(),
      box.read(BoxName.email).toString(),
    ); // Navigate to home
  }
}
