import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/navigation_provider.dart';
import '../routes/app_routes.dart';

class AppNavigationObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _updateNavigationState(route);
    debugPrint('Navigation: Push ${route.settings.name}');
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    if (previousRoute != null) {
      _updateNavigationState(previousRoute);
    } else {
      // 이전 라우트가 없으면 Provider의 히스토리를 사용
      _handlePopWithProvider();
    }
    debugPrint('Navigation: Pop ${route.settings.name}');
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    if (previousRoute != null) {
      _updateNavigationState(previousRoute);
    }
    debugPrint('Navigation: Remove ${route.settings.name}');
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute != null) {
      _updateNavigationState(newRoute);
    }
    debugPrint(
        'Navigation: Replace ${oldRoute?.settings.name} with ${newRoute?.settings.name}');
  }

  void _updateNavigationState(Route<dynamic> route) {
    if (navigator?.context == null) return;

    final routeName = route.settings.name;
    if (routeName == null) return;

    // 메인 화면('/')은 하단 탭으로 상태를 관리하므로
    // 모달 닫힘 등으로 인해 홈 탭으로 강제 전환하지 않도록 무시한다.
    if (routeName == AppRoutes.main || routeName == '/') {
      return;
    }

    // build 완료 후 업데이트하도록 변경
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (navigator?.context == null) return;

      try {
        final context = navigator!.context;
        final navigationProvider =
            Provider.of<NavigationProvider>(context, listen: false);
        navigationProvider.updateByRoute(routeName);
      } catch (e) {
        debugPrint('Failed to update navigation state: $e');
      }
    });
  }

  void _handlePopWithProvider() {
    if (navigator?.context == null) return;

    // build 완료 후 업데이트하도록 변경
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (navigator?.context == null) return;

      try {
        final context = navigator!.context;
        final navigationProvider =
            Provider.of<NavigationProvider>(context, listen: false);
        navigationProvider.pop();
      } catch (e) {
        debugPrint('Failed to handle pop with provider: $e');
      }
    });
  }
}
