import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:laki_icu_app/models/bo/bluetooth_read_model.dart';
import 'package:laki_icu_app/models/bo/user_model.dart';

class StorageService {
  static const String _keyToken = 'auth_token';
  static const String _keyTokenExpiry = 'auth_token_expiry';
  static const String _keyRefreshToken = 'auth_refresh_token';
  static const String _keyRememberPhone = 'remember_phone';
  static const String _keyRememberSmsCode = 'remember_sms_code';
  static const String _keyRememberEnabled = 'remember_enabled';
  static const String _keyUserInfo = 'user_info';
  static const String _keyBluetoothReadSn = 'bluetooth_read_sn';
  static const String _legacyKeyUserSn = 'user_sn';
  static const String _keyClientId = 'client_id';
  static const String _keyBoundBluetoothDeviceId = 'bound_bluetooth_device_id';
  static const String _keyBoundBluetoothDeviceName =
      'bound_bluetooth_device_name';

  final FlutterSecureStorage _storage = const FlutterSecureStorage(
    aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
    ),
  );

  // ==================== Token 相关 ====================

  Future<void> saveToken(String token, {int expiryHours = 24}) async {
    await _storage.write(key: _keyToken, value: token);
    final expiryTime =
        DateTime.now().add(Duration(hours: expiryHours)).millisecondsSinceEpoch;
    await _storage.write(key: _keyTokenExpiry, value: expiryTime.toString());
  }

  Future<String?> getToken() async {
    return await _storage.read(key: _keyToken);
  }

  Future<int?> getTokenExpiry() async {
    final value = await _storage.read(key: _keyTokenExpiry);
    if (value == null) return null;
    return int.tryParse(value);
  }

  Future<bool> isTokenExpired() async {
    final expiry = await getTokenExpiry();
    if (expiry == null) return false;
    return DateTime.now().millisecondsSinceEpoch > expiry;
  }

  Future<void> deleteToken() async {
    await _storage.delete(key: _keyToken);
    await _storage.delete(key: _keyTokenExpiry);
  }

  Future<bool> hasToken() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  // ==================== RefreshToken 相关 ====================

  Future<void> saveRefreshToken(String refreshToken) async {
    await _storage.write(key: _keyRefreshToken, value: refreshToken);
  }

  Future<String?> getRefreshToken() async {
    return await _storage.read(key: _keyRefreshToken);
  }

  Future<void> deleteRefreshToken() async {
    await _storage.delete(key: _keyRefreshToken);
  }

  // ==================== 用户信息相关 ====================

  Future<void> saveUserInfo(UserModel userInfo) async {
    final jsonStr =
        '${userInfo.id}|${userInfo.nickname ?? ''}|${userInfo.phone ?? ''}|${userInfo.avatar ?? ''}|${userInfo.type ?? ''}|${userInfo.canControlDevice ?? ''}|${userInfo.canViewOperation ?? ''}|${userInfo.hospitalId ?? ''}|${userInfo.hospitalName ?? ''}';
    await _storage.write(key: _keyUserInfo, value: jsonStr);
  }

  Future<UserModel?> getUserInfo() async {
    final value = await _storage.read(key: _keyUserInfo);
    if (value == null || value.isEmpty) return null;
    final parts = value.split('|');
    if (parts.length < 9) return null;
    return UserModel(
      id: int.tryParse(parts[0]) ?? 0,
      nickname: parts[1].isEmpty ? null : parts[1],
      phone: parts[2].isEmpty ? null : parts[2],
      avatar: parts[3].isEmpty ? null : parts[3],
      type: parts[4].isEmpty ? null : int.tryParse(parts[4]),
      canControlDevice: parts[5].isEmpty ? null : parts[5],
      canViewOperation: parts[6].isEmpty ? null : parts[6],
      hospitalId: parts[7].isEmpty ? null : parts[7],
      hospitalName: parts[8].isEmpty ? null : parts[8],
    );
  }

  Future<void> deleteUserInfo() async {
    await _storage.delete(key: _keyUserInfo);
  }

  // ==================== 蓝牙读取信息相关 ====================

  Future<void> saveBluetoothReadSn(String sn) async {
    await _storage.write(key: _keyBluetoothReadSn, value: sn);
    await _storage.delete(key: _legacyKeyUserSn);
  }

  Future<BluetoothReadModel> getBluetoothReadInfo() async {
    final sn = await _storage.read(key: _keyBluetoothReadSn) ??
        await _storage.read(key: _legacyKeyUserSn);
    return BluetoothReadModel(sn: sn);
  }

  Future<void> deleteBluetoothReadInfo() async {
    await _storage.delete(key: _keyBluetoothReadSn);
    await _storage.delete(key: _legacyKeyUserSn);
  }

  // ==================== ClientId 相关 ====================

  Future<void> saveClientId(String clientId) async {
    await _storage.write(key: _keyClientId, value: clientId);
  }

  Future<String?> getClientId() async {
    return await _storage.read(key: _keyClientId);
  }

  Future<void> deleteClientId() async {
    await _storage.delete(key: _keyClientId);
  }

  // ==================== 蓝牙绑定相关 ====================

  Future<void> saveBoundBluetoothDevice({
    required String deviceId,
    required String deviceName,
  }) async {
    await _storage.write(key: _keyBoundBluetoothDeviceId, value: deviceId);
    await _storage.write(key: _keyBoundBluetoothDeviceName, value: deviceName);
  }

  Future<Map<String, String?>> getBoundBluetoothDevice() async {
    final deviceId = await _storage.read(key: _keyBoundBluetoothDeviceId);
    final deviceName = await _storage.read(key: _keyBoundBluetoothDeviceName);
    return {
      'deviceId': deviceId,
      'deviceName': deviceName,
    };
  }

  Future<void> deleteBoundBluetoothDevice() async {
    await _storage.delete(key: _keyBoundBluetoothDeviceId);
    await _storage.delete(key: _keyBoundBluetoothDeviceName);
  }

  // ==================== 记住密码相关 ====================

  Future<void> saveRememberCredentials({
    required String phone,
    required String smsCode,
  }) async {
    await _storage.write(key: _keyRememberPhone, value: phone);
    await _storage.write(key: _keyRememberSmsCode, value: smsCode);
    await _storage.write(key: _keyRememberEnabled, value: 'true');
  }

  Future<Map<String, String?>> getRememberCredentials() async {
    final enabled = await _storage.read(key: _keyRememberEnabled);
    if (enabled != 'true') {
      return {'phone': null, 'smsCode': null};
    }
    final phone = await _storage.read(key: _keyRememberPhone);
    final smsCode = await _storage.read(key: _keyRememberSmsCode);
    return {'phone': phone, 'smsCode': smsCode};
  }

  Future<void> clearRememberCredentials() async {
    await _storage.delete(key: _keyRememberPhone);
    await _storage.delete(key: _keyRememberSmsCode);
    await _storage.delete(key: _keyRememberEnabled);
  }

  // ==================== 清空所有数据 ====================

  Future<void> clearAll() async {
    await _storage.deleteAll();
  }
}
