import 'package:flutter/widgets.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../model/auth/login_token_response_model.dart';
import '../networking/restful_api_viewmodel.dart';
import '../preference/data_preference.dart';
import '../base/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;
    if (token == null || token.isEmpty) {
      _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 {
        _handleRefreshFailure();
      }
    } catch (e) {
      print('Token refresh error: $e');
      _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) {
      print('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
  void _handleRefreshFailure() {
    DataPreference.instance.clearData();
    for (final callback in _callbacks) {
      callback(false);
    }
    _callbacks.clear();
    
    // Redirect về login screen (ensure on UI thread)
    WidgetsBinding.instance.addPostFrameCallback((_) {
      AppNavigator.showAuthAlertAndGoLogin('Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.');
    });
  }

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