import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';
import '../configs/constants.dart';
import '../preference/data_preference.dart';
import '../resources/base_color.dart';
import '../shared/router_gage.dart';
import '../widgets/alert/custom_alert_dialog.dart';
import '../widgets/alert/data_alert_model.dart';
import '../widgets/alert/popup_data_model.dart';

class AppNavigator {
  static final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
  static bool _authDialogShown = false;
  static bool _networkDialogShown = false;
  static bool _errorDialogShown = false;
  static bool _defaultDialogShown = false;

  static bool get isShowingDialog =>
      _authDialogShown || _networkDialogShown || _errorDialogShown || _defaultDialogShown;

  static BuildContext? get _ctx => key.currentContext;

  static Future<void> showAuthAlertAndGoLogin(String message) async {
    final description = ErrorCodes.tokenInvalidMessage;
    if (_authDialogShown || _ctx == null) return;
    if (Get.isDialogOpen ?? false) Get.back();
    _authDialogShown = true;
    final dataAlert = DataAlertModel(
      title: "Thông Báo",
      description: description, // message.isNotEmpty ? message : ,
      localHeaderImage: "assets/images/ic_pipi_03.png",
      buttons: [
        AlertButton(
          text: "Đã hiểu",
          onPressed: () async {
            _authDialogShown = false;
            final fallbackMessage = message.isNotEmpty ? message : description;
            if (kIsWeb) {
              await DataPreference.instance.clearData();
              Get.offAllNamed(onboardingScreen);
              // final closed = await webCloseApp({
              //   'message': fallbackMessage,
              //   'timestamp': DateTime.now().millisecondsSinceEpoch,
              // });
              // if (!closed) {
              //   Get.offAllNamed(onboardingScreen);
              // }
              return;
            }
            final phone = DataPreference.instance.phoneNumberUsedForLoginScreen;
            if (phone.isNotEmpty) {
              await DataPreference.instance.clearLoginToken();
              Get.offAllNamed(loginScreen, arguments: {'phone': phone});
            } else {
              await DataPreference.instance.clearData();
              Get.offAllNamed(onboardingScreen);
            }
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
      ],
    );
    Get.dialog(CustomAlertDialog(alertData: dataAlert, showCloseButton: false), barrierDismissible: false).then((_) {
      // Reset flag khi dialog đóng bằng barrierDismissible hoặc cách khác
      if (_authDialogShown) {
        _authDialogShown = false;
      }
    });
  }

  static Future<void> showNoInternetAlert(String message, Callback retry, Callback close) async {
    if (_networkDialogShown || _ctx == null) return;
    _networkDialogShown = true;
    final dataAlert = DataAlertModel(
      title: "Thông Báo",
      description: message.isNotEmpty ? message : ErrorCodes.serverErrorMessage,
      localHeaderImage: "assets/images/ic_pipi_03.png",
      buttons: [
        AlertButton(
          text: "Thử lại",
          onPressed: () {
            _networkDialogShown = false;
            Get.back();
            retry();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(
          text: "Đóng",
          onPressed: () {
            _networkDialogShown = false;
            Get.back();
            close();
          },
          bgColor: BaseColor.second300,
          textColor: Colors.white,
        ),
      ],
    );
    Get.dialog(
      CustomAlertDialog(alertData: dataAlert, showCloseButton: false, direction: ButtonsDirection.row),
      barrierDismissible: false,
    ).then((_) {
      // Reset flag khi dialog đóng bằng barrierDismissible hoặc cách khác
      if (_networkDialogShown) {
        _networkDialogShown = false;
      }
    });
  }

  static void showAlertError({
    required String content,
    bool? barrierDismissible,
    String headerImage = "assets/images/ic_pipi_03.png",
    bool showCloseButton = false,
    VoidCallback? onConfirmed,
  }) {
    debugPrint("Show alert error: $_errorDialogShown");
    if (_errorDialogShown) return;
    final context = _ctx ?? Get.context ?? Get.overlayContext;
    if (context == null) {
      debugPrint('⚠️ AppNavigator: Unable to show alert, no context available');
      return;
    }
    _errorDialogShown = true;
    Get.dialog(
      CustomAlertDialog(
        showCloseButton: showCloseButton,
        alertData: DataAlertModel(
          localHeaderImage: headerImage,
          title: "",
          description: content,
          buttons: [
            AlertButton(
              text: "Đã Hiểu",
              onPressed: () {
                _errorDialogShown = false;
                Get.back();
                if (onConfirmed != null) {
                  onConfirmed();
                }
              },
              bgColor: BaseColor.primary500,
              textColor: Colors.white,
            ),
          ],
        ),
      ),
      barrierDismissible: barrierDismissible ?? false,
    ).then((_) {
      // Reset flag khi dialog đóng bằng barrierDismissible hoặc cách khác
      if (_errorDialogShown) {
        _errorDialogShown = false;
      }
    });
  }

  static void showPopup({
    required PopupDataModel data,
    bool? barrierDismissible,
    bool showCloseButton = false,
    ButtonsDirection direction = ButtonsDirection.column,
    bool force = false,
  }) {
    showAlert(
      data: data.dataAlertModel,
      barrierDismissible: barrierDismissible ?? true,
      showCloseButton: showCloseButton,
      direction: direction,
      force: force,
    );
  }

  static void showAlert({
    required DataAlertModel data,
    bool? barrierDismissible,
    bool showCloseButton = true,
    ButtonsDirection direction = ButtonsDirection.column,
    bool force = false,
  }) {
    if (force) {
      _defaultDialogShown = false;
      if (Get.isDialogOpen ?? false) Get.back();
    }
    if (_defaultDialogShown || _ctx == null) return;
    _defaultDialogShown = true;

    // Wrap buttons với callback để reset flag
    final wrappedData = DataAlertModel(
      localHeaderImage: data.localHeaderImage,
      urlHeaderImage: data.urlHeaderImage,
      title: data.title,
      description: data.description,
      content: data.content,
      buttons:
          data.buttons?.map((button) {
            if (button == null) return null;
            return AlertButton(
              text: button.text,
              textColor: button.textColor,
              bgColor: button.bgColor,
              onPressed: () {
                // Gọi callback gốc trước
                button.onPressed();
                // Sau đó reset flag
                _defaultDialogShown = false;
              },
            );
          }).toList(),
    );

    Get.dialog(
      CustomAlertDialog(alertData: wrappedData, showCloseButton: showCloseButton, direction: direction),
      barrierDismissible: barrierDismissible ?? false,
    ).then((_) {
      // Reset flag khi dialog đóng bằng barrierDismissible hoặc cách khác
      if (_defaultDialogShown) {
        _defaultDialogShown = false;
      }
    });
  }
}
