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

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

class ProfileController extends GetxController {
  RxBool isLoginPage = true.obs;

  RxBool isLoggedIn = false.obs;

  @override
  void onInit() {
    debugPrint(' ProfileController onInit');
    _setLoginStatus();
    super.onInit();
  }

  @override
  void onClose() {
    super.onClose();
  }

  Future<void> onLogoutTapped() async {
    // Get.toNamed(path);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(Constants.IS_LOGGED_IN, false);
    setLoginStatus(false);
    prefs.clear();

    isLoggedIn.value = false;
    update();

    onPageChange(2);
  }

  Future<void> _setLoginStatus() async {
    debugPrint('setLoginStatus');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    isLoggedIn.value = prefs.getBool(Constants.IS_LOGGED_IN) ?? false;
    update();
  }

  void onPageChange(int currPage) {
    debugPrint('onPageChange $currPage');
    // Active Page
    // 1 => LoginPage
    // 2 => RegisterPage

    // current page is login page, set it to false to navigate other page
    if (currPage == 1) {
      isLoginPage.value = false;
      update();
    } else {
      isLoginPage.value = true;
      update();
    }
  }

  Future<void> onDeleteAccountTapped(BuildContext context) async {
    debugPrint('onDeleteAccountTapped');

    showMyAlertDialog(
      context: context,
      callback: (value) async {
        // dismiss the dialog
        Navigator.of(context, rootNavigator: true).pop('dialog');
        if (value) {
          context.loaderOverlay.show();
          final result = await AuthApi.deleteAccount();
          context.loaderOverlay.hide();
          if (result) await onLogoutTapped();
        }
      },
      title: 'are_you_sure'.tr + '!',
      content: 'delete_account_warning'.tr,
      continueBtnTxt: 'ok'.tr,
      cancelBtnTxt: 'cancel'.tr,
    );
  }
}
