import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import '../../base/base_response_model.dart';
import '../../base/restful_api_viewmodel.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) {
        print("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!);
        _getUserProfile();
      } else {
        Get.offNamed(loginScreen, arguments: 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.to(MainTabScreen());
        }
      } else {
        DataPreference.instance.clearLoginToken();
        Get.offNamed(loginScreen, arguments: phoneNumber);
      }
    });
  }
}
