import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:real_estate_mobile/core/services/push_notification_service.dart';
import 'package:real_estate_mobile/core/widgets/app_bottom_nav_bar.dart';
import 'package:real_estate_mobile/features/home/presentation/widgets/home_header.dart';

/// Root shell that provides the persistent header and bottom nav bar.
/// Only the content area (child) swaps when navigating between tabs.
class AppShell extends StatefulWidget {
  final Widget child;

  const AppShell({super.key, required this.child});

  @override
  State<AppShell> createState() => _AppShellState();
}

class _AppShellState extends State<AppShell> {
  @override
  void initState() {
    super.initState();
    // Wire push notification taps to GoRouter navigation
    PushNotificationService().onNotificationTap = (actionUrl) {
      if (!mounted) return;
      if (actionUrl == null || actionUrl.isEmpty) {
        context.go('/notifications');
        return;
      }
      // Translate web routes to mobile routes
      final mobileRoute = _translateRoute(actionUrl);
      context.go(mobileRoute);
    };
  }

  /// Translate web-style actionUrl to mobile route.
  String _translateRoute(String url) {
    final uri = Uri.parse(url);
    final path = uri.path;

    // Message notification: /user/message?conversationId=xxx or /agent/message?conversationId=xxx
    if (path.contains('/message')) {
      final convId = uri.queryParameters['conversationId'];
      if (convId != null && convId.isNotEmpty) {
        return '/messages/chat/$convId';
      }
      return '/messages';
    }

    // Connection request/network
    if (path.contains('/network')) {
      // Agent sees network, user sees agent search
      if (path.startsWith('/agent')) {
        return '/agent/network';
      }
      return '/agents/search';
    }

    // Profile routes
    if (path.contains('/profiles') || path.contains('/profile')) {
      return '/home';
    }

    // If it's already a valid mobile route, use as-is
    if (path.startsWith('/messages') ||
        path.startsWith('/home') ||
        path.startsWith('/notifications') ||
        path.startsWith('/agents')) {
      return path;
    }

    // Fallback
    return '/notifications';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          SafeArea(
            bottom: false,
            child: const HomeHeader(),
          ),
          Expanded(
            child: widget.child,
          ),
        ],
      ),
      bottomNavigationBar: const AppBottomNavBar(),
    );
  }
}
