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 token => _loginToken?.accessToken;
  String? get phone => _profile?.workerSite?.phoneNumber;
  bool get logged => (token ?? "").isNotEmpty;

  Future<void> saveUserProfile(ProfileResponseModel profile) async {
    final prefs = await SharedPreferences.getInstance();
    profile = profile;
    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 {
    final prefs = await SharedPreferences.getInstance();
    _loginToken = token;
    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 {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('login_token');
    _loginToken = null;
  }

  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);
    }
  }
}