import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:tm_app/core/routes/app_shell/desktop_shell_page.dart';
import 'package:tm_app/core/routes/app_shell/mobile_shell_page.dart';
import 'package:tm_app/core/routes/app_shell/tablet_shell_page.dart';
import 'package:tm_app/view_models/home_view_model.dart';
import 'package:tm_app/view_models/tenders_view_model.dart';
import 'package:tm_app/views/shared/responsive_builder.dart';

import '../../../view_models/notification_view_model.dart';

class AppShellScreen extends StatelessWidget {
  const AppShellScreen({required this.navigationShell, super.key});

  final StatefulNavigationShell navigationShell;

  void _gotoBranch(int index, BuildContext context) {
    if (index == navigationShell.currentIndex) {
      return;
    }

    // Navigate first
    navigationShell.goBranch(
      index,
      initialLocation: index == navigationShell.currentIndex,
    );

    // Then trigger data loading after navigation is complete
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (index == 0) {
        context.read<HomeViewModel>().init();
      }
      if (index == 1) {
        context.read<TendersViewModel>().init(context);
      }
      if (index == 3) {
        context.read<NotificationViewModel>().init();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      mobile: SafeArea(
        child: MobileShellPage(
          navigationShell: navigationShell,
          onTap: (value) => _gotoBranch(value, context),
        ),
      ),
      tablet: TabletShellPage(
        navigationShell: navigationShell,
        onTap: (value) => _gotoBranch(value, context),
      ),
      desktop: DesktopShellPage(
        navigationShell: navigationShell,
        onTap: (value) => _gotoBranch(value, context),
      ),
    );
  }
}
