import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../shared/widgets/base_view/base_response_model.dart';
import '../../core/firebase/push_token_service.dart';
import '../../core/network/restful_api_viewmodel.dart';
import '../../core/services/biometric_manager.dart';
import '../../shared/preferences/data_preference.dart';
import '../../shared/router_gage.dart';
import '../biometric/biometric_screen.dart';

abstract class ICreatePasswordRepository {
  late String phoneNumber;
  Future<BaseResponseModel<EmptyCodable>> setPassword(String password);
}

class SignUpCreatePasswordRepository extends RestfulApiViewModel implements ICreatePasswordRepository {
  @override
  late String phoneNumber;
  SignUpCreatePasswordRepository(this.phoneNumber);
  final BiometricManager _biometricManager = BiometricManager();

  @override
  Future<BaseResponseModel<EmptyCodable>> setPassword(String password) async {
    showLoading();
    return client.signup(phoneNumber, password).then((value) {
      hideLoading();
      if (value.status == "success" || value.code == 200) {
        debugPrint("signup success");
        _autoLogin(password);
      }
      return value;
    });
  }

  void _autoLogin(String password) {
    showLoading();
    client.login(phoneNumber, password).then((response) async {
      hideLoading();
      if (response.isSuccess && response.data != null) {
        await DataPreference.instance.saveLoginToken(response.data!);
        await PushTokenService.uploadIfLogged();
        _getUserProfile();
      } else {
        Get.offNamed(loginScreen, arguments: {'phone': phoneNumber});
      }
    });
  }

  void _getUserProfile() {
    showLoading();
    client.getUserProfile().then((value) async {
      hideLoading();
      final userProfile = value.data;
      if (value.isSuccess && userProfile != null) {
        await DataPreference.instance.saveUserProfile(userProfile);
        if (await _biometricManager.canCheckBiometrics()) {
          Get.to(BiometricAuthScreen());
        } else {
          Get.toNamed(mainScreen);
        }
      } else {
        DataPreference.instance.clearLoginToken();
        Get.offNamed(loginScreen, arguments: {'phone': phoneNumber});
      }
    });
  }
}
