import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../app.dart';

class RegisterController extends GetxController {
  RxBool isLoading = false.obs;

  ProfileController _profileController = Get.put(ProfileController());

  final formKey = GlobalKey<FormState>();

  TextEditingController firstNameCtrl = new TextEditingController();
  TextEditingController lastNameCtrl = new TextEditingController();
  TextEditingController phoneCtrl = new TextEditingController();
  TextEditingController passwordCtrl = new TextEditingController();

  @override
  void dispose() {
    firstNameCtrl.dispose();
    lastNameCtrl.dispose();
    phoneCtrl.dispose();
    passwordCtrl.dispose();
    super.dispose();
  }

  Future<void> register() async {
    debugPrint('on create account tapped');

    if (formKey.currentState!.validate()) {
      isLoading.value = true;
      update();

      final maskedPhoneNumber = phoneCtrl.value.text;
      final phone = maskedPhoneNumber.replaceAll(RegExp(r'\D+'), '');

      /* final verificationCode = await AuthApi.getVerificationCode(phone);

      if (verificationCode == null) {
        isLoading.value = false;
        update();
        showSnack('error'.tr, 'can_not_send_sms'.tr, SnackType.ERROR);
        await Future.delayed(Duration(seconds: 4));
        return;
      } */

      final Map<String, dynamic> params = {
        'first_name': firstNameCtrl.text.trim(),
        'last_name': lastNameCtrl.text.trim(),
        'phone': phone,
        'password': passwordCtrl.text.trim(),
        'device_name': await getDeviceName(),
      };

      isLoading.value = false;

      update();

      // Get.to(() => OTPPage(params: params, verificationCode: verificationCode));

      final result = await AuthApi.registerUser(params);

      update();

      if (result) {
        setLoginStatus(result);
        _profileController.onInit();
      }
    }
  }
}
