import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../base/base_response_model.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../firebase/push_token_service.dart';
import '../../permission/biometric_manager.dart';
import '../../preference/data_preference.dart';
import '../../shared/router_gage.dart';
import '../biometric/biometric_screen.dart';
import '../main_tab_screen/main_tab_screen.dart';
import '../splash/splash_screen_viewmodel.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});
      }
    });
  }
}
