import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:uuid/uuid.dart';
import '../screen/webview/web_view_screen.dart';
import '../shared/router_gage.dart';
import 'directional_action_type.dart';

class DirectionalScreen {
  final String? clickActionType;
  final String? clickActionParam;

  const DirectionalScreen._({this.clickActionType, this.clickActionParam});

  factory DirectionalScreen.fromJson(Map<String, dynamic> json) => DirectionalScreen._(
    clickActionType: json['click_action_type'] as String?,
    clickActionParam: json['click_action_param'] as String?,
  );

  Map<String, dynamic> toJson() => {
    'click_action_type': clickActionType,
    'click_action_param': clickActionParam,
  };

  static DirectionalScreen? build({String? clickActionType, String? clickActionParam}) {
    if ((clickActionType ?? "").isEmpty) return null;
    if (clickActionType == "VIEW_APP_SCREEN") {
      return DirectionalScreen._(clickActionType: clickActionParam, clickActionParam: null);
    }
    return DirectionalScreen._(clickActionType: clickActionType, clickActionParam: clickActionParam);
  }

  static DirectionalScreen? buildByName({required DirectionalScreenName name, String? clickActionParam}) {
    if (name == DirectionalScreenName.appScreen) {
      return DirectionalScreen._(clickActionType: clickActionParam, clickActionParam: null);
    }
    return DirectionalScreen._(clickActionType: name.rawValue, clickActionParam: clickActionParam);
  }

  @immutable
  bool begin() {
    final type = DirectionalScreenNameExtension.fromRawValue(clickActionType ?? "");
    if (type == null) {
      print("Không nhận diện được action type: $clickActionType");
      return false;
    }
    switch (type) {
      case DirectionalScreenName.setting:
        Get.toNamed(settingScreen);
        return true;
      case DirectionalScreenName.productOwnVoucher:
        Get.toNamed(voucherDetailScreen, arguments: {"customerProductId": int.parse(clickActionParam ?? "")});
        return true;
      case DirectionalScreenName.customerSupport:
        Get.toNamed(supportScreen);
        return true;
      case DirectionalScreenName.viewDeepLink || DirectionalScreenName.link:
        BaseWebViewInput input = BaseWebViewInput(url: clickActionParam ?? "");
        Get.toNamed(baseWebViewScreen, arguments: input);
        return true;
      case DirectionalScreenName.website:
        Get.toNamed(campaignDetailScreen, arguments: {"id": clickActionParam ?? ""});
        return true;
      case DirectionalScreenName.gameCenter:
        Get.toNamed(vplayGameCenterScreen);
        return true;
      case DirectionalScreenName.viewAllVoucher:
        Get.toNamed(vouchersScreen, arguments: {"enableSearch": true});
        return true;
      case DirectionalScreenName.news:
        Get.toNamed(newsListScreen);
        return true;
      case DirectionalScreenName.gifts:
        Get.toNamed(achievementListScreen);
        return true;
      case DirectionalScreenName.pointHunting || DirectionalScreenName.achievement:
        Get.toNamed(achievementListScreen, arguments: true);
        return true;
      case DirectionalScreenName.myPurchaseItems || DirectionalScreenName.myPurchaseItemsWaitingList:
        Get.toNamed(myVoucherListScreen);
        return true;
      case DirectionalScreenName.orderMenu:
        Get.toNamed(orderMenuScreen);
        return true;
      case DirectionalScreenName.topup || DirectionalScreenName.mobileTopup:
        Get.toNamed(phoneTopUpScreen);
        return true;
      case DirectionalScreenName.productMobileCard:
        Get.toNamed(productMobileCardScreen);
        return true;
      case DirectionalScreenName.simService:
        BaseWebViewInput input = BaseWebViewInput(url: "https://mypoint.uudaigoicuoc.com/");
        Get.toNamed(baseWebViewScreen, arguments: input);
        return true;
      case DirectionalScreenName.mobileTopupData:
        Get.toNamed(dataNetworkServiceScreen);
        return true;
      case DirectionalScreenName.pointBack:
        Get.toNamed(affiliateTabScreen, arguments: {"can_back_button": true});
        return true;
      case DirectionalScreenName.gamesBundle:
        Get.toNamed(gameTabScreen, arguments: {"can_back_button": true});
        return true;
      case DirectionalScreenName.vnTraPackage || DirectionalScreenName.familyMedon || DirectionalScreenName.voucher:
        Get.toNamed(voucherDetailScreen, arguments: {"productId": int.parse(clickActionParam ?? "")});
        return true;
      case DirectionalScreenName.viewDeepLink || DirectionalScreenName.viewDeepLinkInApp:
        if ((clickActionParam ?? "").isEmpty) return true;
        const replaceId1 = '{{customerId}}';
        const replaceId2 = '{customerId}';
        final customerId = DataPreference.instance.profile?.workerSite?.customerId ?? "";
        String urlString = clickActionParam!.urlDecoded;
        if (urlString.contains(replaceId1)) {
          urlString = urlString.replaceAll(replaceId1, customerId);
        }
        if (urlString.contains(replaceId2)) {
          urlString = urlString.replaceAll(replaceId2, customerId);
        }
        // Parse thành Uri và thêm query aff_sub3
        Uri? uri = Uri.tryParse(urlString);
        if (uri == null) return true;
        final requestId = const Uuid().v4(); // Cần package `uuid`
        final updatedUri = uri.replace(queryParameters: {...uri.queryParameters, 'aff_sub3': requestId});
        LaunchMode mode = type == DirectionalScreenName.viewDeepLink ? LaunchMode.externalApplication : LaunchMode.inAppWebView;
        // forceOpen(url: updatedUri, mode: mode);
        safeOpenUrl(updatedUri, preferred: mode);
        return true;
      case DirectionalScreenName.refundHistory:
        Get.toNamed(historyPointCashBackScreen);
        return true;
      case DirectionalScreenName.inviteFriend:
        Get.toNamed(inviteFriendCampaignScreen);
        return true;
      case DirectionalScreenName.dailyCheckin || DirectionalScreenName.dailyCheckinScreen:
        Get.toNamed(dailyCheckInScreen);
        return true;
      case DirectionalScreenName.favorite:
        Get.toNamed(vouchersScreen, arguments: {"favorite": true});
        return true;
      case DirectionalScreenName.transactionHistories:
        Get.toNamed(transactionHistoryScreen);
        return true;
      case DirectionalScreenName.electricBill:
        Get.toNamed(electricPaymentScreen);
        return true;
      case DirectionalScreenName.listPaymentOfElectric:
        Get.toNamed(electricPaymentHistoryScreen);
        return true;
      case DirectionalScreenName.myVnTraPackage:
        Get.toNamed(trafficServiceScreen);
        return true;
      case DirectionalScreenName.campaignSevenDayScreen:
        Get.toNamed(campaignSevenDayScreen);
        return true;
      case DirectionalScreenName.workerProfile:
        Get.toNamed(personalEditScreen);
        return true;
      case DirectionalScreenName.surveyCampaign:
        if ((clickActionParam ?? '').isEmpty) return false;
        Get.toNamed(surveyQuestionScreen,  arguments: {"quizId": clickActionParam ?? ''});
        return true;
      case DirectionalScreenName.myMobileCard:
        Get.toNamed(myMobileCardListScreen);
        return true;
      case DirectionalScreenName.bankAccountManager:
        Get.toNamed(bankAccountManagerScreen);
        return true;
      case DirectionalScreenName.pointHistory:
        Get.toNamed(historyPointScreen);
        return true;
      case DirectionalScreenName.qrCode:
        Get.toNamed(qrCodeScreen);
        return true;
      default:
        print("Không nhận diện được action type: $clickActionType");
        return false;
    }
  }
}

Future<bool> forceOpen({required Uri url, LaunchMode mode = LaunchMode.platformDefault}) async {
  print("force open ${url.toString()}");
  if (await canLaunchUrl(url)) {
    await launchUrl(
      url,
      mode: LaunchMode.inAppBrowserView,
      webViewConfiguration: const WebViewConfiguration(enableJavaScript: true, headers: <String, String>{}),
    );
    return true;
  }
  return false;
}

Future<void> openAppStore(String url) async {
  final uri = Uri.parse(url);
  if (await canLaunchUrl(uri)) {
    await launchUrl(
      uri,
      mode: LaunchMode.externalApplication,
    );
  } else {
    debugPrint("⚠️ Không thể mở URL: $url");
  }
}

Future<bool> safeOpenUrl(Uri url, {LaunchMode preferred = LaunchMode.platformDefault,}) async {
  try {
    // 1) Thử theo mode ưa thích
    if (await canLaunchUrl(url)) {
      final ok = await launchUrl(
        url,
        mode: preferred,
        webViewConfiguration: const WebViewConfiguration(
          enableJavaScript: true,
          headers: <String, String>{},
        ),
      );
      if (ok) return true;
    }
    // 2) Fallback: mở bằng app ngoài (trình duyệt hệ thống)
    if (await canLaunchUrl(url)) {
      final ok = await launchUrl(
        url,
        mode: LaunchMode.externalApplication,
        webViewConfiguration: const WebViewConfiguration(
          enableJavaScript: true,
          headers: <String, String>{},
        ),
      );
      if (ok) return true;
    }
    // 3) Fallback: mở trong webview của app (Custom Tabs / SFSafariViewController)
    if (await canLaunchUrl(url)) {
      final ok = await launchUrl(
        url,
        mode: LaunchMode.inAppBrowserView, // hoặc inAppWebView (tuỳ version url_launcher)
        webViewConfiguration: const WebViewConfiguration(
          enableJavaScript: true,
          headers: <String, String>{},
        ),
      );
      if (ok) return true;
    }
    // 4) Fallback cuối
    if (await canLaunchUrl(url)) {
      final ok = await launchUrl(url, mode: LaunchMode.platformDefault);
      if (ok) return true;
    }
  } catch (e) {
    // ghi log lỗi nếu có
    // debugPrint('safeOpenUrl error: $e');
  }
  return false;
}
