import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../model/auth/login_token_response_model.dart';
import '../model/auth/profile_response_model.dart';

class DataPreference {
  static final DataPreference _instance = DataPreference._internal();
  static DataPreference get instance => _instance;
  DataPreference._internal();

  LoginTokenResponseModel? _loginToken;
  ProfileResponseModel? _profile;
  ProfileResponseModel? get profile => _profile;
  LoginTokenResponseModel? get loginToken => _loginToken;

  String? get phone => _profile?.workerSite?.phoneNumber;

  Future<bool> get logged async {
    final currentToken = await token;
    return (currentToken ?? "").isNotEmpty;
  }

  Future<String?> get token async {
    if (_loginToken != null) {
      return _loginToken?.accessToken;
    } else {
      await loadLoginToken();
      return _loginToken?.accessToken;
    }
  }

  Future<void> saveUserProfile(ProfileResponseModel profile) async {
    _profile = profile;
    final prefs = await SharedPreferences.getInstance();
    final jsonString = jsonEncode(profile.toJson());
    await prefs.setString('user_profile', jsonString);
  }

  Future<void> loadProfile() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonString = prefs.getString('user_profile');
    if (jsonString != null) {
      final jsonMap = jsonDecode(jsonString);
      _profile = ProfileResponseModel.fromJson(jsonMap);
    }
  }

  Future<void> saveLoginToken(LoginTokenResponseModel token) async {
    _loginToken = token;
    final prefs = await SharedPreferences.getInstance();
    final jsonString = jsonEncode(token.toJson());
    await prefs.setString('login_token', jsonString);
  }

  Future<void> loadLoginToken() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonString = prefs.getString('login_token');
    if (jsonString != null) {
      final jsonMap = jsonDecode(jsonString);
      _loginToken = LoginTokenResponseModel.fromJson(jsonMap);
    }
  }

  Future<void> clearLoginToken() async {
    _loginToken = null;
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('login_token');
  }

  Future<void> clearBioToken(String phone) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('biometric_login_token_$phone');
  }

  Future<void> saveBioToken(String bioToken) async {
    if (phone == null) return;
    final prefs = await SharedPreferences.getInstance();
    final jsonString = jsonEncode(bioToken);
    await prefs.setString('biometric_login_token_$phone', jsonString);
  }

  Future<String?> getBioToken(String phone) async {
    final prefs = await SharedPreferences.getInstance();
    final jsonString = prefs.getString('biometric_login_token_$phone');
    if (jsonString != null) {
      return jsonDecode(jsonString);
    }
  }
}