import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/providers/page_provider.dart';
import 'package:initial_folder/screens/course/my_course_page.dart';
import 'package:initial_folder/screens/profile/profile_page.dart';
import 'package:initial_folder/screens/search_course/search_page.dart';
import 'package:initial_folder/screens/whislist/my_whislist_page.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:provider/provider.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'components/home_page.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);
  static String routeName = "/home";

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

class _HomeScreenState extends State<HomeScreen> {
  Widget buildNavItem(int index, String icon, String activeIcon, String title) {
    PageProvider pageProvider = Provider.of<PageProvider>(context);
    return GestureDetector(
      onTap: () {
        pageProvider.currentIndex = index;
      },
      child: Container(
        width: getProportionateScreenWidth(360) / 5,
        decoration: BoxDecoration(
          color: pageProvider.currentIndex == index
              ? Theme.of(context).brightness == Brightness.light
        ? primaryColorligtmode
        : primaryColor
    : Colors.transparent,
          borderRadius: BorderRadius.circular(5),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedContainer(
              duration: Duration(milliseconds: 300),
              height: getProportionateScreenHeight(22),
              width: getProportionateScreenWidth(22),
              child: SvgPicture.asset(
                pageProvider.currentIndex == index ? activeIcon : icon,
                color: pageProvider.currentIndex == index
                    ? baruTextutih
                    : Theme.of(context).colorScheme.secondary,
              ),
            ),
            SizedBox(height: getProportionateScreenHeight(2)),
            Text(
              title,
              style: thirdTextStyle.copyWith(
                color: pageProvider.currentIndex == index
                    ? baruTextutih
                    : Theme.of(context).colorScheme.secondary,
                fontSize: getProportionateScreenWidth(10),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    UsersInfo().getIdUser().then((value) {
      print(value);
      FirebaseMessaging.instance.subscribeToTopic("payment-before-paid-$value");
      FirebaseMessaging.instance.subscribeToTopic("payment-after-paid-$value");
      FirebaseMessaging.instance.subscribeToTopic("qna-new-qna-$value");
      FirebaseMessaging.instance.subscribeToTopic("qna-reply-qna-$value");
      FirebaseMessaging.instance.subscribeToTopic("alert-carts-$value");
    });
    UsersInfo().getToken().then((value) => print(value));
    PageProvider pageProvider = Provider.of<PageProvider>(context);
    DateTime backButtonPressTime = DateTime.now();

    SizeConfig().init(context);
    Future<bool> handleWillPop(BuildContext context) async {
      final now = DateTime.now();
      final backButtonHasNotBeenPressedOrSnackBarHasBeenClosed =
          DateTime.now().difference(backButtonPressTime) >=
              Duration(milliseconds: 500);

      if (backButtonHasNotBeenPressedOrSnackBarHasBeenClosed) {
        backButtonPressTime = now;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            width: 240,
            duration: Duration(seconds: 2),
            backgroundColor: secondaryColor,
            content: Text(
              'Tekan sekali lagi untuk keluar',
              style: primaryTextStyle.copyWith(
                  color: backgroundColor, fontSize: 12),
              textAlign: TextAlign.center,
            ),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20),
            ),
          ),
        );
        return false;
      }

      return true;
    }

    Widget customBottomNavigation() {
      return Container(
        color: Theme.of(context).brightness == Brightness.dark
            ? twelveColor
            : baruTextutih,
        height: getProportionateScreenHeight(48),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            buildNavItem(0, 'assets/icons/featured.svg',
                'assets/icons/featured_click.svg', 'Home'),
            buildNavItem(1, 'assets/icons/search.svg',
                'assets/icons/search_click.svg', 'Search'),
            buildNavItem(2, 'assets/icons/my_course.svg',
                'assets/icons/my_course_click.svg', 'My Course'),
            buildNavItem(3, 'assets/icons/wishlist.svg',
                'assets/icons/wishlist_click.svg', 'Wishlist'),
            buildNavItem(4, 'assets/icons/profile.svg',
                'assets/icons/profile_click.svg', 'Profile'),
          ],
        ),
      );
    }

    Widget body() {
      switch (pageProvider.currentIndex) {
        case 0:
          return HomePage();
        case 1:
          return SearchPage();
        case 2:
          return MyCoursePage();
        case 3:
          return WishlistPage();
        case 4:
          return ProfilePage();
        default:
          return HomePage();
      }
    }

    return WillPopScope(
      onWillPop: () => handleWillPop(context),
      child: Scaffold(
        backgroundColor: pageProvider.currentIndex == 1
            ? Theme.of(context).brightness == Brightness.dark
                ? twelveColor
                : baruTextutih
            : Theme.of(context).brightness == Brightness.dark
                ? backgroundColor
                : baruTextutih,
        body: body(),
        bottomNavigationBar: customBottomNavigation(),
      ),
    );
  }
}
