import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:search_engine/screens/home.dart';
import 'package:search_engine/screens/search.dart';
import 'package:persistent_bottom_nav_bar_v2/persistent_bottom_nav_bar_v2.dart'
    as nav;

class GlobalNavigator extends StatefulWidget {
  const GlobalNavigator({super.key});

  @override
  _GlobalNavigatorState createState() => _GlobalNavigatorState();

  static void navigateToIndex(BuildContext context, int index) {
    final navigatorState =
        context.findAncestorStateOfType<_GlobalNavigatorState>();
    navigatorState?._navigateToIndex(index);
  }
}

class _GlobalNavigatorState extends State<GlobalNavigator> {
  late nav.PersistentTabController _controller;

  @override
  void initState() {
    super.initState();
    _controller = nav.PersistentTabController(initialIndex: 0);
  }

  List<nav.PersistentTabConfig> _navBarsItems() {
    return [
      nav.PersistentTabConfig(
          screen: const SearchPage(),
          item: nav.ItemConfig(
            icon: const Icon(Icons.search),
            title: "search".tr(),
            activeForegroundColor: const Color(0xFF871818),
            inactiveForegroundColor: Colors.grey,
          )),
      nav.PersistentTabConfig(
          screen: const HomePage(),
          item: nav.ItemConfig(
            icon: const Icon(Icons.book),
            title: "title".tr(),
            activeForegroundColor: const Color(0XFF6b8e23),
            inactiveForegroundColor: Colors.grey,
          ))
    ];
  }

  void _navigateToIndex(int index) {
    if (mounted) {
      setState(() {
        _controller.jumpToTab(index);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return nav.PersistentTabView(
      navBarBuilder: (navBarConfig) => nav.Style2BottomNavBar(
        navBarConfig: navBarConfig,
        navBarDecoration: nav.NavBarDecoration(color: Colors.transparent),
      ),
      controller: _controller,
      tabs: _navBarsItems(),
      backgroundColor: Colors.white,
      handleAndroidBackButtonPress: true,
      resizeToAvoidBottomInset: true,
      gestureNavigationEnabled: true,
      stateManagement: true,
      screenTransitionAnimation: nav.ScreenTransitionAnimation(
          curve: Easing.emphasizedDecelerate,
          duration: Duration(milliseconds: 150)),
    );
  }
}
