import 'dart:async';

// import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/providers/incomplete_profile_provider.dart';
// import 'package:initial_folder/providers/notification_provider.dart';
import 'package:initial_folder/providers/user_info_provider.dart';
// import 'package:initial_folder/screens/home/components/notification.dart';
import 'package:initial_folder/screens/home/home_screen.dart';
import 'package:initial_folder/screens/login/login_screen.dart';
import 'package:initial_folder/screens/login/login_with_email/login_email_screen.dart';
import 'package:initial_folder/screens/profile/account_sign_in/incomplete_profile_screen.dart';
import 'package:initial_folder/providers/firebase_authentication_provider.dart';
import 'package:initial_folder/providers/page_provider.dart';
import 'package:initial_folder/screens/splash/intro_screen.dart';
import 'package:initial_folder/services/auth_service.dart';
import 'package:initial_folder/theme.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../size_config.dart';

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

  static String routeName = "/splash";

  @override
  State<SplashScreenLogin> createState() => _SplashScreenLoginState();
}

class Condition {
  static bool loginFirebase = false;
  static bool loginEmail = false;
}

class _SplashScreenLoginState extends State<SplashScreenLogin>
    with TickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    duration: const Duration(seconds: 1),
    vsync: this,
  )..forward();
  late final Animation<double> _animation = CurvedAnimation(
    parent: _controller,
    curve: Curves.easeIn,
  );

  @override
  void initState() {
    super.initState();
    // getIntroScreen();
    Timer(const Duration(seconds: 3), () {
      if (mounted) {
        isLogin();
      }
    });
  }

  void isLogin() async {
    var token = await UsersInfo().getToken();
    var email = await UsersInfo().getEmail();
    var stateintro = await UsersInfo().getStateintro();

    var isTokenExpired = await AuthService().checkToken(token);
    print("Token expired? ${isTokenExpired}");
    if (isTokenExpired) {
      print('masuk sini');
      UsersInfo().logout();
      Provider.of<FirebaseAuthenticationProvider>(context, listen: false)
          .logout();
      Provider.of<PageProvider>(context, listen: false).remove();
      Navigator.of(context).pushNamedAndRemoveUntil(
          LoginScreen.routeName, (Route<dynamic> route) => false);

      print("state intro ${stateintro}");
      if (stateintro == 'true') {
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(
            builder: (context) => LoginEmail(),
          ),
        );
      } else {
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(
            builder: (context) => introScreen(),
          ),
        );
      }
    } else {
      await Provider.of<UserInfoProvider>(context, listen: false)
          .getUserInfo(email);

      Condition.loginFirebase = true;
      Condition.loginEmail = true;

      if (!mounted) return;
      IncompleteProfileProvider userInfoIncomplete =
          Provider.of<IncompleteProfileProvider>(context, listen: false);
      await userInfoIncomplete.getUserInfoIncomplete();
      print("User info incomplete ${userInfoIncomplete.isUserInfoComplete}");
      if (userInfoIncomplete.isUserInfoComplete == null) {
        Navigator.of(context).pushNamedAndRemoveUntil(
            LoginEmail.routeName, (Route<dynamic> route) => false);
        return;
      }

      if (userInfoIncomplete.isUserInfoComplete!) {
        Navigator.of(context).pushNamedAndRemoveUntil(
            HomeScreen.routeName, (Route<dynamic> route) => false);
      } else {
        Navigator.of(context).pushNamedAndRemoveUntil(
            IncompleteProfile.routeName, (Route<dynamic> route) => false);
      }
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final Brightness brightnessValue =
        MediaQuery.of(context).platformBrightness;
    bool isDarkMode = brightnessValue == Brightness.dark;
    String imagePath = Theme.of(context).brightness == Brightness.dark
        ? "assets/images/VOCASIA logo.png"
        : "assets/images/Logo2.png";

    SizeConfig().init(context);
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Flexible(
              flex: 10,
              child: FadeTransition(
                opacity: _animation,
                child: Container(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        imagePath,
                        width: getProportionateScreenWidth(140),
                      ),
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: Text(
                          'Make You Competent',
                          style: primaryTextStyle.copyWith(
                              fontSize: getProportionateScreenHeight(11),
                              color: fourthColor),
                        ),
                      )
                      // SizedBox(
                      //   height: getProportionateScreenHeight(10),
                      // ),
                      // Text(
                      //   "Make You Competent",
                      //   style: primaryTextStyle.copyWith(
                      //       fontWeight: reguler,
                      //       fontSize: getProportionateScreenWidth(12.0),
                      //       color: secondaryColor),
                      // ),
                    ],
                  ),
                ),
              ),
            ),
            Flexible(
              flex: 1,
              child: Padding(
                padding: EdgeInsets.only(
                    bottom: getProportionateScreenHeight(
                        25)), // Ubah sesuai kebutuhan Anda
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: CircularProgressIndicator(
                    color: Colors.white,
                    strokeWidth: 3,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
