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

import '../../../app.dart';

class PersonalInfoController extends GetxController {
  // Personal Info
  final personalInfoForm = GlobalKey<FormState>();
  final TextEditingController nameCtrl = new TextEditingController();
  final TextEditingController surnameCtrl = new TextEditingController();
  final TextEditingController phoneCtrl = new TextEditingController();
  final TextEditingController pwdCtrl = new TextEditingController();

  RxBool isLoading = false.obs;
  RxBool isErrorOccurred = false.obs;

  RxBool obscureText = true.obs;

  @override
  void onInit() {
    debugPrint('PersonalInfoController onInit');
    getCurrentUser();
    super.onInit();
  }

  @override
  void onClose() {
    nameCtrl.dispose();
    surnameCtrl.dispose();
    phoneCtrl.dispose();
    pwdCtrl.dispose();
    super.onClose();
  }

  void onVisibilityChange() {
    obscureText.value = !obscureText.value;
    update();
  }

  Future<void> getCurrentUser() async {
    isLoading.value = true;
    update();

    final UserModel? userModel = await AuthApi.getCurrentUser();

    if (userModel == null) {
      isLoading.value = false;
      isErrorOccurred.value = true;
      update();
      return;
    }

    nameCtrl.text = userModel.firstName;
    surnameCtrl.text = userModel.lastName;
    phoneCtrl.text = userModel.phone;

    isLoading.value = false;
    update();
  }

  Future<void> updateProfile() async {
    final maskedPhoneNumber = phoneCtrl.value.text;
    final phone = maskedPhoneNumber.replaceAll(RegExp(r'\D+'), '');

    final Map<String, dynamic> params = {
      'first_name': nameCtrl.text,
      'last_name': surnameCtrl.text,
      'phone': phone,
      'password': pwdCtrl.text.trim(),
    };

    isLoading.value = true;
    update();

    SnackType snackType = SnackType.INFO;
    String title = 'Success';

    String? message = await AuthApi.updateUser(params);

    if (message == null) {
      snackType = SnackType.ERROR;
      title = 'Error';
      message = 'Can not update profile';
    }

    showSnack(title, message, snackType);

    isLoading.value = false;
    update();
  }
}
