import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_service/constant/links.dart';
import 'package:siro_service/controller/functions/crud.dart';
import 'package:siro_service/controller/functions/device_helper.dart';
import 'package:siro_service/print.dart';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class RegisterController extends GetxController {
  final firstName = TextEditingController();
  final lastName = TextEditingController();
  final email = TextEditingController();
  final phone = TextEditingController();
  final password = TextEditingController();
  
  final FlutterSecureStorage storage = const FlutterSecureStorage();
  final formKey = GlobalKey<FormState>();

  var isLoading = false.obs;

  void register() async {
    if (formKey.currentState!.validate()) {
      isLoading.value = true;
      
      // الحصول على البصمة
      String fingerprint = await DeviceHelper.getDeviceFingerprint();
      
      var payload = {
        "first_name": firstName.text,
        "last_name": lastName.text,
        "email": email.text,
        "phone": phone.text,
        "password": password.text,
        "fingerprint": fingerprint,
      };

      Log.print('🚀 Register Payload: $payload');
      var res = await CRUD().post(link: AppLink.register, payload: payload);
      Log.print('📥 Register Response: $res');

      isLoading.value = false;

      if (res != 'failure' && res is Map && res['status'] == 'success') {
        // حفظ كلمة المرور للدخول التلقائي لاحقاً
        await storage.write(key: 'password', value: password.text);

        // Request OTP
        bool otpSent = await _sendOtp(phone.text);
        if (otpSent) {
          _showOtpDialog(phone.text, res['message']?['message'] ?? "تم تقديم طلبك بنجاح. يرجى انتظار موافقة الإدارة.");
        } else {
          Get.snackbar('Error', 'Failed to send OTP'.tr);
        }
      } else {
        Get.snackbar(
          "خطأ",
          res is Map ? res['message'].toString() : "فشل تقديم طلب التسجيل",
          backgroundColor: Colors.red.withOpacity(0.7),
          colorText: Colors.white,
        );
      }
    }
  }

  Future<bool> _sendOtp(String phoneNumber) async {
    try {
      final response = await CRUD().post(
        link: '${AppLink.server}/auth/otp/request.php',
        payload: {
          'receiver': phoneNumber,
          'user_type': 'service'
        },
      );
      return response != 'failure';
    } catch (e) {
      Log.print('OTP SEND ERROR: $e');
      return false;
    }
  }

  void _showOtpDialog(String phoneNumber, String successMessage) {
    String otpCode = '';
    Get.defaultDialog(
      title: 'رمز التحقق'.tr,
      content: Column(
        children: [
          Text('تم إرسال رمز التحقق إلى رقمك ($phoneNumber)'.tr),
          const SizedBox(height: 16),
          TextField(
            onChanged: (val) => otpCode = val,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              hintText: 'أدخل الرمز هنا'.tr,
              border: OutlineInputBorder(),
            ),
          ),
        ],
      ),
      textConfirm: 'تحقق'.tr,
      confirmTextColor: Colors.white,
      onConfirm: () async {
        if (otpCode.length >= 3) {
          Get.back(); // close dialog
          await _verifyOtpAndFinalize(phoneNumber, otpCode, successMessage);
        } else {
          Get.snackbar('خطأ', 'الرجاء إدخال رمز صحيح'.tr);
        }
      },
    );
  }

  Future<void> _verifyOtpAndFinalize(String phoneNumber, String otp, String successMessage) async {
    Get.dialog(const Center(child: CircularProgressIndicator()), barrierDismissible: false);
    try {
      final response = await CRUD().post(
        link: '${AppLink.server}/auth/otp/verify.php',
        payload: {
          'phone_number': phoneNumber,
          'token_code': otp,
          'user_type': 'service',
        },
      );
      Get.back(); // close loading

      if (response != 'failure' && response['status'] == 'success') {
        Get.defaultDialog(
          title: "نجاح".tr,
          middleText: successMessage,
          onConfirm: () {
            Get.back(); // close success dialog
            Get.back(); // return to login page
          },
          textConfirm: "موافق".tr,
        );
      } else {
        Get.snackbar('Error', 'Invalid OTP'.tr);
      }
    } catch (e) {
      Get.back(); // close loading
      Log.print('OTP VERIFY ERROR: $e');
      Get.snackbar('Error', e.toString());
    }
  }

  @override
  void onClose() {
    firstName.dispose();
    lastName.dispose();
    email.dispose();
    phone.dispose();
    password.dispose();
    super.onClose();
  }
}
