import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/page/authentication/authentication.dart';
import 'package:e_commerce_training/src/page/category/category.dart';
import 'package:e_commerce_training/src/page/category/category_page.dart';
import 'package:e_commerce_training/src/page/home/home.dart';
import 'package:e_commerce_training/src/page/home/home_page.dart';
import 'package:e_commerce_training/src/page/main/main.dart';
import 'package:e_commerce_training/src/page/main/main_cubit.dart';
import 'package:e_commerce_training/src/page/notification/notification.dart';
import 'package:e_commerce_training/src/page/notification/notification_page.dart';
import 'package:e_commerce_training/src/page/search/search.dart';
import 'package:e_commerce_training/src/page/search/search_page.dart';
import 'package:e_commerce_training/src/page/setting/setting.dart';
import 'package:e_commerce_training/src/page/setting/setting_page.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:persistent_bottom_nav_bar/persistent-tab-view.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  PersistentTabController _controller = PersistentTabController(initialIndex: 0);
  List listImg = [
    "https://files.betacorp.vn/files/ecm/2021/03/26/1702x621-chinh-thuc-godzilla-112933-260321-16.jpg",
    "https://files.betacorp.vn/files/ecm/2021/03/19/1702x621-hp7-133727-190321-16.jpg",
    "https://files.betacorp.vn/files/ecm/2021/03/08/1702x621-minari-133332-080321-88.jpg",
    "https://files.betacorp.vn/files/ecm/2021/01/06/1702x621-nhuong-quyen-182208-060121-79.jpg",
    "https://files.betacorp.vn/files/ecm/2021/02/26/1702x621-141710-260221-49.jpg",
  ];
  int page = 1;
  int _currentIndex = 0;
  late MainCubit _cubit;
  late AuthenticationCubit _authCubit;
  late NotificationCubit _notificationCubit;
  late SearchCubit _searchCubit;
  late HomeCubit _homeCubit;
  late SettingCubit _settingCubit;
  late CategoryCubit _categoryCubit;
  GlobalKey<NavigatorState> _currentTabKey = GlobalKey<NavigatorState>();
  final GlobalKey<NavigatorState> homeNavKey = GlobalKey<NavigatorState>();
  final GlobalKey<NavigatorState> notificationNavKey = GlobalKey<NavigatorState>();
  final GlobalKey<NavigatorState> myOrderNavKey = GlobalKey<NavigatorState>();
  final GlobalKey<NavigatorState> listNewsNavKey = GlobalKey<NavigatorState>();
  final GlobalKey<NavigatorState> settingNavKey = GlobalKey<NavigatorState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    AppRepository repository = AppRepository();

    _cubit = MainCubit(repository);
    _cubit.getCountNotification();
    _cubit.getHomeConfig();
    _controller.addListener(() {
    _currentIndex = _controller.index;
    _cubit.selectTab(_currentIndex);

    });

    _authCubit = BlocProvider.of<AuthenticationCubit>(context);
    _homeCubit = HomeCubit(repository);
    _categoryCubit = CategoryCubit(repository);
    _searchCubit = SearchCubit(repository);
    _notificationCubit = NotificationCubit(repository);
    _settingCubit = SettingCubit(repository);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MultiBlocProvider(
        providers: [
          BlocProvider.value(value: _authCubit),
          BlocProvider<MainCubit>(
            create: (_) => _cubit,
          ),
          BlocProvider<NotificationCubit>(
            create: (_) => _notificationCubit,
          ),
          BlocProvider<HomeCubit>(
            create: (_) => _homeCubit,
          ),
          BlocProvider<SearchCubit>(
            create: (_) => _searchCubit,
          ),
          BlocProvider<CategoryCubit>(
            create: (_) => _categoryCubit,
          ),
          BlocProvider<SettingCubit>(
            create: (_) => _settingCubit,
          ),
        ],
        child: BlocConsumer<MainCubit, MainState>(
          listener: (context, state) {
            if (state is GetNewNotificationSuccess) {
              _cubit.getCountNotification();
            }
            if (state is MainFailure) Util.showErrorSnackBar(context, state.error);
            if (state is NavigateToNotificationState) {
              if (_currentIndex != Const.NOTIFICATION) _cubit.getCountNotification();
            }
            if (state is MainPageState) {
              _currentIndex = state.position;
              _controller.jumpToTab(_currentIndex);
            }
          },
          builder: (context, state) {
            return PersistentTabView(
              context,
              controller: _controller,
              screens: _buildScreens(),
              items: _navBarsItems(),
              confineInSafeArea: true,
              backgroundColor: Colors.white,
              // Default is Colors.white.
              handleAndroidBackButtonPress: true,
              // Default is true.
              resizeToAvoidBottomInset: true,
              // This needs to be true if you want to move up the screen when keyboard appears. Default is true.
              stateManagement: true,
              // Default is true.
              hideNavigationBarWhenKeyboardShows: true,
              // Recommended to set 'resizeToAvoidBottomInset' as true while using this argument. Default is true.
              decoration: NavBarDecoration(
                  borderRadius: BorderRadius.circular(10.0),
                  colorBehindNavBar: Colors.white,
                  boxShadow: [
                    BoxShadow(color: Colors.grey.withOpacity(0.3), spreadRadius: 5, blurRadius: 7, offset: Offset(0, 3))
                  ]),
              popAllScreensOnTapOfSelectedTab: true,
              popActionScreens: PopActionScreensType.all,
              itemAnimationProperties: ItemAnimationProperties(
                // Navigation Bar's items animation properties.
                duration: Duration(milliseconds: 200),
                curve: Curves.ease,
              ),
              screenTransitionAnimation: ScreenTransitionAnimation(
                // Screen transition animation on change of selected tab.
                animateTabTransition: true,
                curve: Curves.ease,
                duration: Duration(milliseconds: 200),
              ),
              navBarStyle: NavBarStyle.style6, // Choose the nav bar style with this property.
            );
          },
        ),
      ),
    );
  }

  List<Widget> _buildScreens() {
    return [
      HomePage(),
      CategoryPage(),
      SearchPage(),
      NotificationPage(),
      SettingPage(),
    ];
  }

  List<PersistentBottomNavBarItem> _navBarsItems() {
    return [
      PersistentBottomNavBarItem(
        icon: Icon(CupertinoIcons.home),
        title: R.string.home.tr(),
        activeColorPrimary: CupertinoColors.activeBlue,
        inactiveColorPrimary: CupertinoColors.systemGrey,
      ),
      PersistentBottomNavBarItem(
        icon: Icon(CupertinoIcons.square_grid_2x2),
        title: R.string.category.tr(),
        activeColorPrimary: CupertinoColors.activeBlue,
        inactiveColorPrimary: CupertinoColors.systemGrey,
      ),
      PersistentBottomNavBarItem(
        icon: Icon(CupertinoIcons.search),
        title: R.string.search.tr(),
        activeColorPrimary: CupertinoColors.activeBlue,
        inactiveColorPrimary: CupertinoColors.systemGrey,
      ),
      PersistentBottomNavBarItem(
        icon: Stack(
          clipBehavior: Clip.none,
          children: [
            Icon(CupertinoIcons.bell),
            Visibility(
              visible: _cubit.countUnRead > 0,
              child: Positioned(
                top: -4,
                right: -4,
                child: Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(2),
                  decoration: BoxDecoration(
                    color: R.color.red,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  constraints: BoxConstraints(
                    minWidth: 18,
                    minHeight: 18,
                  ),
                  child: Text(
                    _cubit.countUnRead > 0 ? _cubit.countUnRead.toString() : "",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
            ),
          ],
        ),
        title: R.string.notification.tr(),
        activeColorPrimary: CupertinoColors.activeBlue,
        inactiveColorPrimary: CupertinoColors.systemGrey,
      ),
      PersistentBottomNavBarItem(
        icon: Icon(CupertinoIcons.person_alt_circle),
        title: R.string.account.tr(),
        activeColorPrimary: CupertinoColors.activeBlue,
        inactiveColorPrimary: CupertinoColors.systemGrey,
      ),
    ];
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _controller.removeListener(() {});
    _controller.dispose();
    super.dispose();
  }
}
