import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_viewmodel.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import '../../base/base_response_model.dart';
import '../../configs/url_params.dart';
import '../../model/auth/login_token_response_model.dart';
import '../../model/auth/profile_response_model.dart';
import '../../web/web_helper_stub.dart';
import 'models/update_response_model.dart';
import '../../preference/data_preference.dart';
import '../../preference/point/point_manager.dart';
import 'package:url_launcher/url_launcher.dart';
import '../popup_manager/popup_manager_viewmodel.dart';

class SplashScreenViewModel extends RestfulApiViewModel {
  var infoAppUpdate = BaseResponseModel<UpdateResponseModel>().obs;
  var isLoading = false.obs;

  void checkUpdateApp() {
    showLoading();
    isLoading(true);
    client.checkUpdateApp().then((value) {
      infoAppUpdate.value = value;
      hideLoading();
      isLoading(false);
    });
  }

  Future<void> openLink() async {
    final updateLink = infoAppUpdate.value.data?.updateRequest?.first?.updateLink ?? "";
    if (updateLink.isEmpty) return;
    final Uri url = Uri.parse(updateLink);
    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    }
  }

  Future<void> makeDataFollowInitApp() async {
    if (DataPreference.instance.logged) {
      _freshUserProfile();
      return;
    }
    final tokenFormWeb = UrlParams.getTokenForApi() ?? "";
    print('🔍 SplashScreen - Token from URL: $tokenFormWeb');
    if (tokenFormWeb.isEmpty) {
      _directionWhenTokenInvalid();
      return;
    }
    print('✅ Token found, proceeding with login');
    LoginTokenResponseModel tokenModel = LoginTokenResponseModel(accessToken: tokenFormWeb);
    await DataPreference.instance.saveLoginToken(tokenModel);
    _freshUserProfile();
    return;
  }

  Future<void> _freshUserProfile() async {
    showLoading();
    final response = await client.getUserProfile();
    hideLoading();
    final userProfile = response.data;
    if (response.isSuccess && userProfile != null) {
      _freshDataAndToMainScreen(userProfile);
    } else {
      DataPreference.instance.clearLoginToken();
      _directionWhenTokenInvalid();
    }
  }

  void _directionWhenTokenInvalid() {
    // TODO: handle later
    Get.toNamed(onboardingScreen);
    // if (kIsWeb) {
    //   print('❌ No token found on web, cannot proceed');
    //   webCloseApp({
    //     'message': 'No token found, cannot proceed',
    //     'timestamp': DateTime.now().millisecondsSinceEpoch,
    //   });
    // } else {
    //   Get.toNamed(onboardingScreen);
    // }
  }
  void _freshDataAndToMainScreen(ProfileResponseModel userProfile) async {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await DataPreference.instance.saveUserProfile(userProfile);
      await UserPointManager().fetchUserPoint();
      await PopupManagerViewModel.instance.ensureLoaded();
      Get.toNamed(mainScreen);
    });
  }
}