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;

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

    final profileJson = prefs.getString('user_profile');
    if (profileJson != null) {
      _profile = ProfileResponseModel.fromJson(jsonDecode(profileJson));
    }
  }

  String? get token => _loginToken?.accessToken;
  String? get phone => _profile?.workerSite?.phoneNumber;
  bool get logged => (token ?? "").isNotEmpty;
  ProfileResponseModel? get profile => _profile;

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

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

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

  Future<void> clearUserProfile() async {
    _profile = null;
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('user_profile');
  }

  Future<void> clearData() async {
    await clearLoginToken();
    await clearUserProfile();
  }

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

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

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