import 'package:flutter/widgets.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../app/config/constants.dart';
import '../../features/login/model/login_token_response_model.dart';
import '../network/restful_api_viewmodel.dart';
import '../../shared/preferences/data_preference.dart';
import '../../app/routing/app_navigator.dart';

class TokenRefreshService extends RestfulApiViewModel {
  static final TokenRefreshService _instance = TokenRefreshService._internal();
  factory TokenRefreshService() => _instance;
  TokenRefreshService._internal();

  bool _isRefreshing = false;
  final List<Function(bool)> _callbacks = [];

  /// Refresh token với retry mechanism
  Future<void> refreshToken(Function(bool) callback) async {
    _callbacks.add(callback);
    if (_isRefreshing) return;
    final token = DataPreference.instance.token;
    final refreshToken = DataPreference.instance.refreshToken;
    if (token.orEmpty.isEmpty || refreshToken.orEmpty.isEmpty) {
      await _handleRefreshFailure();
      return;
    }
    _isRefreshing = true;
    try {
      final response = await client.refreshToken().timeout(const Duration(seconds: 10));
      if (response.isSuccess && response.data != null) {
        final token = LoginTokenResponseModel.fromRefreshToken(response.data!);
        await DataPreference.instance.saveLoginToken(token);
        await _getUserProfileAfterRefresh();
        _handleRefreshSuccess();
      } else {
        await _handleRefreshFailure();
      }
    } catch (e) {
      debugPrint('Token refresh error: $e');
      await _handleRefreshFailure();
    } finally {
      _isRefreshing = false;
    }
  }

  /// Lấy user profile sau khi refresh token thành công
  Future<void> _getUserProfileAfterRefresh() async {
    try {
      final response = await client.getUserProfile();
      if (response.isSuccess && response.data != null) {
        await DataPreference.instance.saveUserProfile(response.data!);
      }
    } catch (e) {
      debugPrint('Get user profile after refresh error: $e');
    }
  }

  /// Xử lý refresh thành công
  void _handleRefreshSuccess() {
    for (final callback in _callbacks) {
      callback(true);
    }
    _callbacks.clear();
  }

  /// Xử lý refresh thất bại - redirect về login
  Future<void> _handleRefreshFailure() async {
    final logged = DataPreference.instance.logged;
    await DataPreference.instance.clearData();
    for (final callback in _callbacks) {
      callback(false);
    }
    _callbacks.clear();
    // Redirect về login screen (ensure on UI thread)
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!logged) return;
      AppNavigator.showAuthAlertAndGoLogin(ErrorCodes.tokenInvalidMessage);
    });
  }

  /// Kiểm tra xem có đang refresh không
  bool get isRefreshing => _isRefreshing;
}
