import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/notification_provider.dart';
import 'package:initial_folder/providers/user_info_provider.dart';
import 'package:initial_folder/screens/cart/cart_page.dart';
import 'package:initial_folder/screens/login/login_with_email/login_email_screen.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:provider/provider.dart';
import '../../../../size_config.dart';
import '../notification.dart';
import 'icon_btn_with_counter.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';

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

  @override
  State<HomeHeader> createState() => _HomeHeaderState();
}

class _HomeHeaderState extends State<HomeHeader> {
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(seconds: 0), () async {
      await Provider.of<NotificationProvider>(context, listen: false)
          .getNotificationCount();
    });
  }

  @override
  Widget build(BuildContext context) {
    UserInfoProvider userInfoProvider = Provider.of<UserInfoProvider>(context);
    FirebaseMessaging.onMessage.listen((event) async {
      if (event.notification!.body!.isNotEmpty) {
        await Provider.of<NotificationProvider>(context, listen: false)
            .getNotificationCount();
      }
    });

    Future _showDialogNotLogin(String teks) {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          elevation: 0.0,
          contentPadding: EdgeInsets.symmetric(
            horizontal: getProportionateScreenWidth(20),
            vertical: getProportionateScreenHeight(20),
          ),
          content: Text(
            'Mohon login terlebih dahulu sebelum $teks',
            style: thirdTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(11)),
          ),
          actions: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Text('Batal',
                  style: primaryTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(12),
                      letterSpacing: 1,
                      color: primaryColor)),
            ),
            SizedBox(width: getProportionateScreenWidth(5)),
            GestureDetector(
              onTap: () {
                Navigator.of(context).pushNamedAndRemoveUntil(
                    LoginEmail.routeName, (Route<dynamic> route) => false);
              },
              child: Text(
                'Login',
                style: primaryTextStyle.copyWith(
                    fontSize: getProportionateScreenWidth(12),
                    letterSpacing: 1,
                    color: primaryColor),
              ),
            ),
          ],
        ),
      );
    }

    handleNotLoginCart() async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        Navigator.of(context, rootNavigator: true).push(
          CustomNavigator(
            child: CartPage(),
          ),
        );
      } else {
        String teks = 'dapat mengakses keranjang';
        return _showDialogNotLogin(teks);
      }
    }

    handleNotLoginNotif() async {
      var token = await UsersInfo().getToken();
      if (token != null || Condition.loginFirebase == true) {
        Navigator.of(context, rootNavigator: true).push(
          CustomNavigator(
            child: Notifikasi(),
          ),
        );
      } else {
        String teks = 'dapat mengakses notifikasi';
        return _showDialogNotLogin(teks);
      }
    }

    return Container(
      height: getProportionateScreenHeight(60),
      child: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: EdgeInsets.only(left: getProportionateScreenWidth(23)),
              child: RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: 'Welcome ${userInfoProvider.fullName}\n',
                      style: thirdTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(12),
                          color: Theme.of(context).brightness == Brightness.dark
                              ? Colors.white
                              : Colors.black),
                    ),
                    TextSpan(
                      text: 'Let\'s\ Explore Course',
                      style: thirdTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(16),
                          fontWeight: bold,
                          color: Theme.of(context).brightness == Brightness.dark
                              ? Colors.white
                              : Colors.black),
                    ),
                  ],
                ),
              ),
            ),
            Row(
              children: [
                Transform.scale(
                  origin: Offset(-11, 0),
                  scale: getProportionateScreenHeight(0.9),
                  child: Container(
                    padding:
                        EdgeInsets.only(right: getProportionateScreenWidth(10)),
                    child: Consumer<NotificationProvider>(
                      builder: (context, value, child) {
                        return IconBtnWithCounter(
                          icon: Theme.of(context).brightness == Brightness.dark
                              ? SvgPicture.asset(
                                  "assets/icons/notification_dark.svg")
                              : SvgPicture.asset(
                                  "assets/icons/notification.svg"),
                          numOfitem:
                              (Condition.loginEmail || Condition.loginFirebase)
                                  ? value.notificationCount
                                  : 0,
                          press: () {
                            handleNotLoginNotif();
                          },
                        );
                      },
                    ),
                  ),
                ),
                !Condition.loginEmail && !Condition.loginFirebase
                    ? Transform.scale(
                        origin: Offset(0, 0),
                        scale: getProportionateScreenHeight(1),
                        child: Container(
                          padding: EdgeInsets.fromLTRB(
                              getProportionateScreenHeight(3),
                              0,
                              getProportionateScreenHeight(3),
                              0),
                          child: IconBtnWithCounter(
                            numOfitem: 0,
                            icon: Theme.of(context).brightness ==
                                    Brightness.dark
                                ? SvgPicture.asset("assets/icons/cart_dark.svg")
                                : SvgPicture.asset("assets/icons/cart.svg"),
                            press: () => handleNotLoginCart(),
                          ),
                        ),
                      )
                    : Transform.scale(
                        origin: Offset(0, 0),
                        scale: getProportionateScreenHeight(1),
                        child: Container(
                          padding: EdgeInsets.fromLTRB(
                              getProportionateScreenHeight(3),
                              0,
                              getProportionateScreenHeight(3),
                              0),
                          child: Consumer<CartsProvider>(
                            builder: (context, state, _) {
                              return IconBtnWithCounter(
                                numOfitem: state.result == null
                                    ? 0
                                    : state.data.length,
                                icon: Theme.of(context).brightness ==
                                        Brightness.dark
                                    ? SvgPicture.asset(
                                        "assets/icons/cart_dark.svg")
                                    : SvgPicture.asset("assets/icons/cart.svg"),
                                press: () => handleNotLoginCart(),
                              );
                            },
                          ),
                        ),
                      ),
                Padding(
                  padding:
                      EdgeInsets.only(left: SizeConfig.blockHorizontal! * 4),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
