import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../model/auth/login_token_response_model.dart';
import '../model/auth/profile_response_model.dart';
import '../screen/popup_manager/popup_manager_viewmodel.dart';
import '../web/web_helper.dart';

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

  LoginTokenResponseModel? _loginToken;
  ProfileResponseModel? _profile;
  String phoneNumberUsedForLoginScreen = "";

  Future<void> init() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final tokenJson = prefs.getString('login_token');
      if (tokenJson != null && tokenJson.isNotEmpty) {
        try {
          _loginToken = LoginTokenResponseModel.fromJson(jsonDecode(tokenJson));
        } catch (e) {
          debugPrint('Failed to parse login token: $e');
          // Clear invalid token
          await prefs.remove('login_token');
        }
      }
      final profileJson = prefs.getString('user_profile');
      if (profileJson != null && profileJson.isNotEmpty) {
        try {
          _profile = ProfileResponseModel.fromJson(jsonDecode(profileJson));
          phoneNumberUsedForLoginScreen = _profile?.workerSite?.phoneNumber ?? "";
        } catch (e) {
          debugPrint('Failed to parse user profile: $e');
          // Clear invalid profile
          await prefs.remove('user_profile');
        }
      }
    } catch (e) {
      debugPrint('DataPreference init failed: $e');
    }
  }
  String get displayName {
    var name = _profile?.workerSite?.fullname ?? "";
    if (name.isEmpty) {
      name = "Quý Khách";
    }
    return name;
  }
  String? get rankName => _profile?.workingSite?.primaryMembership?.membershipLevel?.levelName ?? "";
  String? get token => _loginToken?.accessToken;
  String? get refreshToken => _loginToken?.refreshToken;
  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;
    phoneNumberUsedForLoginScreen = _profile?.workerSite?.phoneNumber ?? "";
    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');
    await PopupManagerViewModel.instance.reset();
  }

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

  Future<void> clearData() async {
    await webClearStore();
    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 {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonString = prefs.getString('biometric_login_token_$phone');
      if (jsonString != null && jsonString.isNotEmpty) {
        try {
          return jsonDecode(jsonString) as String?;
        } catch (e) {
          debugPrint('Failed to parse bio token for $phone: $e');
          // Clear invalid bio token
          await prefs.remove('biometric_login_token_$phone');
          return null;
        }
      }
      return null;
    } catch (e) {
      debugPrint('getBioToken failed for $phone: $e');
      return null;
    }
  }

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