import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/model/Article.dart';
import 'package:flutter/material.dart';
import 'package:top_news_app/providers/article_provider.dart';
import 'package:top_news_app/screen/email_login_screen.dart';
import 'package:top_news_app/screen/news_details_screen.dart';
import 'package:top_news_app/screen/register_screen.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:top_news_app/services/auth_service.dart';
import 'package:top_news_app/services/storage_service.dart';

import '../model/auth.dart';

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

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  var auth = Auth();
  bool _isLoading = true;
  bool isAuth = false;
  var storage = StorageService();
  List<ArticleData> splashList = [];
  var articleProvider = ArticleProvider();

  var authService = AuthService();
  int currentPageIndex = 0;
  bool get isLastPage => currentPageIndex == splashList.length - 1;
  var pageController = PageController();


  forwardAction(context) {
    if (isLastPage) {
      Navigator.pushNamed(context, '/main-screen');
    } else {
      pageController.nextPage(
          duration: const Duration(milliseconds: 300), curve: Curves.ease);
    }
  }

  getAuthData() async {
    try{
      splashList = (await articleProvider.getTopPosts())!;
      redirect();
      isAuth = (await storage.isAuthInLocal())!;
      if(isAuth){
        auth = await storage.getAuthUserDataFromStorage();
      }
    }catch(e){
      rethrow;
    }

    setState(() {
      _isLoading = false;
    });
  }

  redirect(){
    if(splashList.isEmpty){
      Navigator.pushNamed(context, '/main-screen');
    }
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getAuthData();

  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      body: SafeArea(
        child: _isLoading ?  Center(
          child: Container(
            height: 200,
            decoration:  BoxDecoration(
              image: DecorationImage(
                  image: Theme.of(context).brightness == Brightness.dark ?   AssetImage(darkLogo) :  AssetImage(lightLogo) ),
            ),
          ),
        ) : Stack(
          children: [
            PageView.builder(
                controller: pageController,
                onPageChanged: (index) {
                  setState(() {
                    currentPageIndex = index;
                  });
                },
                itemCount: splashList.length,
                itemBuilder: (context, index) {
                  if (splashList.length != index+1) {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          height: size.height / 1.8,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: NetworkImage(
                                    splashList[index].thumbnail!),
                                fit: BoxFit.cover),
                            gradient: LinearGradient(
                              begin: Alignment.topRight,
                              end: Alignment.bottomLeft,
                              colors: [
                                Theme.of(context)
                                    .primaryColor
                                    .withOpacity(0.9),
                                Colors.grey.withOpacity(0.2),
                              ],
                            ),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                            children: [
                              customSizeBox(18),
                              GestureDetector(
                                onTap: (){
                                  Navigator.push(context, MaterialPageRoute(builder: (context)=> NewsDetailsScreen(data: splashList[index])));
                                },
                                child: Text('${splashList[index].title}',
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.robotoSerif(
                                        fontWeight: FontWeight.w600, fontSize: 22)),
                              ),
                              customSizeBox(12),
                              Padding(
                                padding:
                                const EdgeInsets.symmetric(horizontal: 28.0),
                                child: Text(
                                  '${splashList[index].shortContent}',
                                  style: GoogleFonts.robotoSerif(
                                      fontWeight: FontWeight.w400),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                              const SizedBox(height: 12),
                            ],
                          ),
                        ),

                      ],
                    );
                  } else {
                    return !isAuth ?  Column(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        Expanded(
                          child: Container(
                            width: double.infinity,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              image: DecorationImage(
                                fit: BoxFit.cover,
                                image: Image.network(
                                  '${splashList[index].thumbnail}',
                                ).image,
                              ),
                            ),
                            child: Container(
                              width: 100,
                              height: 100,
                              decoration:  BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [
                                    const Color(0x00FFFFFF),
                                    Theme.of(context).brightness == Brightness.dark ? Colors.black : Colors.white,
                                  ],
                                  stops: const [0, 1],
                                  begin: const AlignmentDirectional(0, -1),
                                  end: const AlignmentDirectional(0, 1),
                                ),
                              ),
                              alignment: const AlignmentDirectional(0.00, 1.00),
                              child: Padding(
                                padding: const EdgeInsetsDirectional.fromSTEB(24, 64, 24, 24),
                                child: Text(
                                  '${splashList[index].title}',
                                  textAlign: TextAlign.center,
                                    style: GoogleFonts.robotoSerif(
                                        fontWeight: FontWeight.w600, fontSize: 22)

                                ),

                              ),
                            ),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsetsDirectional.fromSTEB(0, 44, 0, 0),
                          child: Column(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 40),
                                child: GestureDetector(
                                  onTap: () {
                                    Navigator.push(context, MaterialPageRoute(builder: (context)=>const RegistrationScreen()));
                                  },
                                  child: Container(
                                    height: 55,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8.0),
                                      color: primaryColorsAccent,
                                    ),
                                    child:  Center(
                                        child: Text(
                                          getTranslated(context, 'Sign up') ?? 'Sign up',
                                          style: GoogleFonts.robotoSerif(fontSize: 16,fontWeight: FontWeight.w500,color: Colors.white),
                                        )),
                                  ),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsetsDirectional.fromSTEB(0, 12, 0, 12),
                                child: Text(
                                  getTranslated(context, 'Or use social media') ?? 'Or use social media',
                                  style: GoogleFonts.robotoSerif(),
                                ),
                              ),

                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 40),
                                child: GestureDetector(
                                  onTap: () {
                                   authService.signInWithFacebook(context);
                                  },
                                  child: Container(
                                    height: 55,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8.0),
                                      border: Border.all(color: Colors.blue,width: 1)
                                    ),
                                    child:  Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        const Icon(Icons.facebook),
                                        const SizedBox(
                                          width: 10,
                                        ),
                                        Text(
                                          getTranslated(context, 'Sign In With Facebook') ?? 'Sign In With Facebook',
                                          style: GoogleFonts.robotoSerif(fontSize: 16,fontWeight: FontWeight.w500),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                              customSizeBox(10),
                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 40),
                                child: GestureDetector(
                                  onTap: () {
                                    authService.signInWithGoogle(context);
                                  },
                                  child: Container(
                                    height: 55,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(8.0),
                                        border: Border.all(color: Colors.red,width: 1)
                                    ),
                                    child:  Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                         const Icon(FontAwesomeIcons.google),
                                        const SizedBox(
                                          width: 10,
                                        ),
                                        Text(
                                          getTranslated(context, 'Sign In With Google') ?? 'Sign In With Google',
                                          style: GoogleFonts.robotoSerif(fontSize: 16,fontWeight: FontWeight.w500),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                              customSizeBox(10),
                              Padding(
                                padding: const EdgeInsetsDirectional.fromSTEB(0, 24, 0, 64),
                                child:  Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        getTranslated(context, 'Already have an account?') ?? 'Already have an account?',
                                        style: GoogleFonts.robotoSerif(color: Colors.grey),
                                      ),
                                      const SizedBox(
                                        width: 10,
                                      ),
                                      GestureDetector(
                                        onTap: (){
                                          Navigator.push(context, MaterialPageRoute(builder: (context)=>const EmailLoginScreen()));
                                        },
                                        child: Text(
                                          getTranslated(context, 'Log In') ?? 'Log In',
                                          style:GoogleFonts.robotoSerif(
                                            fontWeight: FontWeight.bold,
                                            color: primaryColors,
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                              ),
                              customSizeBox(60),
                            ],
                          ),
                        ),
                      ],
                    ) : Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          height: size.height / 1.8,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: NetworkImage(
                                    splashList[index].thumbnail!),
                                fit: BoxFit.cover),
                            gradient: LinearGradient(
                              begin: Alignment.topRight,
                              end: Alignment.bottomLeft,
                              colors: [
                                Theme.of(context)
                                    .primaryColor
                                    .withOpacity(0.9),
                                Colors.grey.withOpacity(0.2),
                              ],
                            ),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Column(
                            children: [
                              customSizeBox(18),
                              GestureDetector(
                                onTap: (){
                                  Navigator.push(context, MaterialPageRoute(builder: (context)=> NewsDetailsScreen(data: splashList[index])));
                                },
                                child: Text('${splashList[index].title}',
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.robotoSerif(
                                        fontWeight: FontWeight.w600, fontSize: 22)),
                              ),
                              customSizeBox(12),
                              Padding(
                                padding:
                                const EdgeInsets.symmetric(horizontal: 28.0),
                                child: Text(
                                  '${splashList[index].shortContent}',
                                  style: GoogleFonts.robotoSerif(
                                      fontWeight: FontWeight.w400),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                              const SizedBox(height: 12),
                            ],
                          ),
                        ),

                      ],
                    );
                  }
                }),
            Positioned(
              bottom: 50,
              left: 25,
              child: Row(
                children: List.generate(
                    splashList.length,
                    (index) => Container(
                          margin: const EdgeInsets.all(4),
                          width: 28,
                          height: 8,
                          decoration: BoxDecoration(
                            color: currentPageIndex == index
                                ? activeDropPointSplashScreen
                                : deactivateDropPointSplashScreen,
                            borderRadius: const BorderRadius.all(Radius.circular(6))
                          ),
                        )),
              ),
            ),
            Positioned(
                right: 25,
                bottom: 40,
                child: GestureDetector(
                  onTap: () {
                    forwardAction(context);
                  },
                  child: Container(
                      padding: const EdgeInsets.symmetric(
                          vertical: 12, horizontal: 20),
                      decoration: BoxDecoration(
                          shape: BoxShape.rectangle,
                          color: primaryColors,
                          borderRadius: BorderRadius.circular(8)),
                      child: Text(
                        'Next',
                        style: GoogleFonts.roboto(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: Colors.white),
                      )),
                )),
          ],
        ),
      ),
    );
  }
}
