import 'dart:math';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:it0_app/l10n/app_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../updater/update_service.dart';
import '../network/connectivity_provider.dart';
import '../widgets/offline_banner.dart';
import '../widgets/floating_robot_fab.dart';
import '../config/app_config.dart';
import '../telemetry/telemetry.dart';
import '../../features/auth/data/providers/auth_provider.dart';
import '../../features/auth/presentation/pages/login_page.dart';
import '../../features/home/presentation/pages/home_page.dart';
import '../../features/my_agents/presentation/pages/my_agents_page.dart';
import '../../features/billing/presentation/pages/billing_overview_page.dart';
import '../../features/profile/presentation/pages/profile_page.dart';
import '../../features/notifications/presentation/providers/notification_providers.dart';
import '../../features/notifications/presentation/pages/notification_inbox_page.dart';
import '../../features/notifications/presentation/pages/notification_preferences_page.dart';
import '../../features/referral/presentation/screens/referral_screen.dart';

// ---------------------------------------------------------------------------
// Router provider
// ---------------------------------------------------------------------------

final routerProvider = Provider<GoRouter>((ref) {
  return GoRouter(
    initialLocation: '/splash',
    routes: [
      GoRoute(
        path: '/splash',
        builder: (context, state) => const _SplashPage(),
      ),
      GoRoute(
        path: '/login',
        builder: (context, state) => const LoginPage(),
      ),
      ShellRoute(
        builder: (context, state, child) => ScaffoldWithNav(child: child),
        routes: [
          GoRoute(
            path: '/home',
            builder: (context, state) => const HomePage(),
          ),
          GoRoute(
            path: '/my-agents',
            builder: (context, state) => const MyAgentsPage(),
          ),
          GoRoute(
            path: '/billing',
            builder: (context, state) => const BillingOverviewPage(),
          ),
          GoRoute(
            path: '/profile',
            builder: (context, state) => const ProfilePage(),
          ),
          GoRoute(
            path: '/referral',
            builder: (context, state) => const ReferralScreen(),
          ),
          GoRoute(
            path: '/notifications/inbox',
            builder: (context, state) => const NotificationInboxPage(),
          ),
          GoRoute(
            path: '/notifications/preferences',
            builder: (context, state) => const NotificationPreferencesPage(),
          ),
        ],
      ),
    ],
  );
});

// ---------------------------------------------------------------------------
// ScaffoldWithNav — 4 tabs + floating robot FAB
// ---------------------------------------------------------------------------

class ScaffoldWithNav extends ConsumerStatefulWidget {
  final Widget child;
  const ScaffoldWithNav({super.key, required this.child});

  static const routes = [
    '/home',
    '/my-agents',
    '/billing',
    '/profile',
  ];

  @override
  ConsumerState<ScaffoldWithNav> createState() => _ScaffoldWithNavState();
}

class _ScaffoldWithNavState extends ConsumerState<ScaffoldWithNav>
    with WidgetsBindingObserver {
  DateTime? _lastUpdateCheck;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkForUpdateIfNeeded();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      ref.read(connectivityProvider.notifier).check();
      _checkForUpdateIfNeeded();
    }
  }

  Future<void> _checkForUpdateIfNeeded() async {
    final updateService = UpdateService();
    if (!updateService.isInitialized) return;
    if (updateService.isShowingUpdateDialog) return;

    if (_lastUpdateCheck != null) {
      final cooldown = 90 + Random().nextInt(210);
      final elapsed =
          DateTime.now().difference(_lastUpdateCheck!).inSeconds;
      if (elapsed < cooldown) return;
    }

    _lastUpdateCheck = DateTime.now();
    await Future.delayed(const Duration(seconds: 3));
    if (!mounted) return;
    await updateService.checkForUpdate(context);
  }

  int _selectedIndex(BuildContext context) {
    final location = GoRouterState.of(context).uri.path;
    for (int i = 0; i < ScaffoldWithNav.routes.length; i++) {
      if (location.startsWith(ScaffoldWithNav.routes[i])) return i;
    }
    return 0;
  }

  @override
  Widget build(BuildContext context) {
    final unreadCount = ref.watch(unreadNotificationCountProvider);
    final currentIndex = _selectedIndex(context);

    return Scaffold(
      body: Column(
        children: [
          const OfflineBanner(),
          Expanded(child: widget.child),
        ],
      ),
      floatingActionButton: const FloatingRobotFab(),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      bottomNavigationBar: NavigationBar(
        selectedIndex: currentIndex,
        destinations: [
          NavigationDestination(
            icon: const Icon(Icons.home_outlined),
            selectedIcon: const Icon(Icons.home),
            label: AppLocalizations.of(context).navHome,
          ),
          NavigationDestination(
            icon: const Icon(Icons.smart_toy_outlined),
            selectedIcon: const Icon(Icons.smart_toy),
            label: AppLocalizations.of(context).navMyAgents,
          ),
          NavigationDestination(
            icon: Badge(
              isLabelVisible: unreadCount > 0,
              label: Text('$unreadCount'),
              child: const Icon(Icons.credit_card_outlined),
            ),
            selectedIcon: const Icon(Icons.credit_card),
            label: AppLocalizations.of(context).navBilling,
          ),
          NavigationDestination(
            icon: const Icon(Icons.person_outline),
            selectedIcon: const Icon(Icons.person),
            label: AppLocalizations.of(context).navProfile,
          ),
        ],
        onDestinationSelected: (index) {
          if (index != currentIndex) {
            GoRouter.of(context).go(ScaffoldWithNav.routes[index]);
          }
        },
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Splash page
// ---------------------------------------------------------------------------

class _SplashPage extends ConsumerStatefulWidget {
  const _SplashPage();

  @override
  ConsumerState<_SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends ConsumerState<_SplashPage> {
  @override
  void initState() {
    super.initState();
    _tryRestore();
  }

  Future<void> _tryRestore() async {
    final config = ref.read(appConfigProvider);
    await TelemetryService().initialize(
      apiBaseUrl: config.apiBaseUrl,
      context: context,
    );

    final auth = ref.read(authStateProvider.notifier);
    final restored = await auth.tryRestoreSession();
    if (!mounted) return;
    if (restored) {
      context.go('/home');
    } else {
      context.go('/login');
    }
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(child: CircularProgressIndicator()),
    );
  }
}
