import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/sevices/app_update_service.dart';

@RoutePage()
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final List<PageRouteInfo> _routes = const [
    EarningsFlowRoute(),
    ShiftsFlowRoute(),
    ProfileMainFlowRoute(),
  ];

  bool _shouldHideBottomNavBar(BuildContext nestedContext) {
    final currentPath = context.router.currentPath;
    return _allowBottomNavBarRoutes
        .any((route) => currentPath == route.toString());
  }

  final List<String> _allowBottomNavBarRoutes = [
    '/home/shifts/list',
    '/home/earnings/list',
    '/home/profile/menu'
  ];

  getMediaQueryData(BuildContext context) {
    if (!_shouldHideBottomNavBar(context)) {
      return MediaQuery.of(context);
    } else {
      //76 - navigation height, 22 - bottom padding
      var newBottomPadding = MediaQuery.of(context).padding.bottom + 76 + 22;
      var newPadding =
          MediaQuery.of(context).padding.copyWith(bottom: newBottomPadding);
      return MediaQuery.of(context).copyWith(padding: newPadding);
    }
  }

  @override
  void initState() {
    // getIt<BackgroundService>().initializeService();
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((call) {
      getIt<AppUpdateService>().checkForUpdate(context);
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: AutoTabsRouter(
        duration: const Duration(milliseconds: 250),
        routes: _routes,
        builder: (context, child) {
          return Stack(
            children: [
              MediaQuery(
                data: getMediaQueryData(context),
                child: child,
              ),
              if (_shouldHideBottomNavBar(context)) _bottomNavBar(context),
            ],
          );
        },
      ),
    );
  }

  Widget _bottomNavBar(context) {
    final tabsRouter = AutoTabsRouter.of(context);
    return Positioned(
      bottom: 22,
      left: 16,
      right: 16,
      child: SafeArea(
        top: false,
        child: Container(
          height: 76,
          padding: const EdgeInsets.symmetric(horizontal: 24),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(38),
            color: AppColors.bgColorDark,
          ),
          child: Row(
            children: [
              _navBarItem('Earnings',
                  Assets.images.icons.navigation.emptyWallet, 0, tabsRouter),
              _navBarItem('Shifts',
                  Assets.images.icons.navigation.clipboardText, 1, tabsRouter),
              _navBarItem('Profile', Assets.images.icons.navigation.profile, 2,
                  tabsRouter),
            ],
          ),
        ),
      ),
    );
  }

  Widget _navBarItem(
    String text,
    SvgGenImage icon,
    int index,
    tabsRouter,
  ) {
    var color = tabsRouter.activeIndex == index
        ? AppColors.navBarActive
        : AppColors.navBarDisabled;
    return Expanded(
      child: GestureDetector(
        onTap: () {
          if (index == tabsRouter.activeIndex && index == 0) {
            (tabsRouter.innerRouterOf(EarningsFlowRoute.name)!).maybePop();
          }
          if (index == tabsRouter.activeIndex && index == 1) {
            (tabsRouter.innerRouterOf(ShiftsFlowRoute.name)!).maybePop();
          }
          if (index == tabsRouter.activeIndex && index == 2) {
            (tabsRouter.innerRouterOf(ProfileMainFlowRoute.name)!).maybePop();
          }
          tabsRouter.setActiveIndex(index);
        },
        child: Container(
          color: Colors.transparent,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              icon.svg(
                colorFilter: ColorFilter.mode(
                  color,
                  BlendMode.srcIn,
                ),
              ),
              const Gap(8),
              Text(
                text.tr(),
                style: (tabsRouter.activeIndex == index
                        ? AppTextStyles.bodyTinyMed
                        : AppTextStyles.bodyTinyReg)
                    .copyWith(color: color),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
