import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:package_info/package_info.dart';
import 'package:rate_my_app/rate_my_app.dart';
import 'package:road24_mobile/data/repository/CarsRepository.dart';
import 'package:road24_mobile/data/response/CarsResponse.dart';
import 'package:road24_mobile/data/shared_data.dart';
import 'package:road24_mobile/data/version_update.dart';
import 'package:road24_mobile/model/blocs/mycar/cars_bloc.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:road24_mobile/view/auth/phone_page.dart';
import 'package:road24_mobile/view/base/update_page.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/firebase.dart';
import 'package:road24_mobile/view/home/dash_board.dart';
import 'package:road24_mobile/view/language/language_choose.dart';
import 'package:road24_mobile/view/mycar/add/add_new_car_first_step.dart';
import 'package:road24_mobile/view/widgets/custom_bottom_tabbar.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:sizer/sizer.dart';
import 'widgets/mono_widget.dart';

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

  static RateMyApp rateMyApp = RateMyApp(
    googlePlayIdentifier: 'uz.kashapp.road24jarimalar',
    appStoreIdentifier: '1543010525',
    minDays: 0,
    minLaunches: 1,
    remindDays: 0,
    remindLaunches: 1,
  );

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

class _SplashScreenState extends State<SplashScreen>
    with TickerProviderStateMixin {
  late AnimationController animationController;
  final ValueNotifier<String?> token = ValueNotifier('');

  bool loading = false;
  VersionType? updateType;

  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  final CarsBloc carsBloc = CarsBloc(repository: CarsRepository());

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    );
    animationController.addListener(() => setState(() {}));
    animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        // _start();

        setState(() => loading = true);
        _setUp();
      }
    });
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      animationController.forward();
    });
  }

  @override
  void dispose() {
    animationController.dispose();
    carsBloc.close();
    token.dispose();
    super.dispose();
  }

  Future<void> _setUpdateType() async {
    try {
      // await FinesManualMixin().getBasicCalculationAmount();

      updateType = await VersionUpdate.updateType();
    } catch (ex) {
      setState(() => loading = false);
      print(ex);
      Config.showSnackBar(
        context,
        ex.toString().replaceAll("Exception: ", "") +
            "\n" +
            S.of(context).try_again,
      );
      print("set update Type exception");
    }
  }

  Future<void> _setUp() async {
    SplashScreen.packageInfo = await PackageInfo.fromPlatform();
    await _setUpdateType();
    if (MyApp.preferences == null) {
      MyApp.preferences = await Preferences.getInstance();
    }
    print("refres...");
    print(MyApp.preferences?.getRefreshToken());
    await Config.getLanguageFromSharedPrefs();
    token.value = MyApp.preferences?.getToken();
    if (MyApp.hasInternet.value) _start();
  }

  Future<void> _start() async {
    try {
      if (updateType == null) {
        updateType = await VersionUpdate.updateType();
        setState(() => loading = false);
      }
      if (updateType != null && updateType != VersionType.NONE) {
        await showDialog(
          barrierDismissible: false,
          context: context,
          builder: (_) => WillPopScope(
            onWillPop: () => Future.value(false),
            child: UpdatePage(
              onSkipped: () => Navigator.pop(context),
              onLaunched: VersionUpdate.launchStore,
              skipped: updateType == VersionType.SMALL,
            ),
          ),
        );
      }
      if (Config.language == "") {
        Navigator.pushReplacement(
          context,
          CupertinoPageRoute(builder: (_) => LanguageChoose()),
        );
      } else {
        if ((token.value != null && token.value != "")) {
          carsBloc.add(GetCars());
        } else {
          Navigator.pushReplacement(
            context,
            CupertinoPageRoute(builder: (_) => PhonePage()),
          );
        }
      }
    } catch (e) {
      print("eroror....$e");
      // MyApp.hasInternet.value = false;
      // if (Config.language == "") {
      //   Navigator.pushReplacement(
      //     context,
      //     CupertinoPageRoute(builder: (_) => LanguageChoose()),
      //   );
      // } else {
      //   if ((token.value != null && token.value != "")) {
      //     carsBloc.add(GetCars());
      //   } else {
      //     Navigator.pushReplacement(
      //       context,
      //       CupertinoPageRoute(builder: (_) => PhonePage()),
      //     );
      //   }
      // }
    }
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: MyApp.hasInternet,
      builder: (context, bool hasInternet, _) {
        if (hasInternet) {
          return BlocListener(
            bloc: carsBloc,
            listener: (context, state) {
              if (state is CarListSuccessState) {
                List<Results> list = state.response.results;
                if (list.isNotEmpty) {
                  FirebaseNotifications().setUpFirebase(context);

                  // await FirebaseNotifications.requestNotificationPermission();
                  DashBoard.activeTab.value =
                      CustomBottomTabBar.indexMap['MyAvto'];

                  Navigator.pushAndRemoveUntil(
                    context,
                    CupertinoPageRoute(builder: (_) => DashBoard()),
                    (route) => false,
                  );
                } else {
                  Navigator.pushAndRemoveUntil(
                    context,
                    CupertinoPageRoute(
                        builder: (_) => AddNewCarFirstStep(
                              isFromRegistrationPage: true,
                            )),
                    // builder: (_) => AddNewCarOrEditPage(
                    //       isFromRegistrationPage: true,
                    //     )),
                    (route) => false,
                  );
                }
              }
            },
            child: Scaffold(
              key: scaffoldKey,
              backgroundColor: Color(0xfff3f3f3),
              body: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: 20.0.w,
                    height: 20.0.w,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      image: DecorationImage(
                        image: AssetImage('assets/png/app_store_logo.png'),
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                  SizedBox(width: double.infinity, height: 2.0.h),
                  Text(
                    "Road24",
                    style: AppStyle.textStyle().copyWith(
                        color: Colors.black,
                        fontWeight: FontWeight.bold,
                        fontSize: 27.0),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 30),
                  MonoWidget(
                    lang: Config.language,
                    progress: animationController.value,
                    style: AppStyle.textStyle().copyWith(
                      color: AppColors.selectedColor,
                      fontSize: 22,
                    ),
                    infoTextColor: AppColors.colorf51a51,
                    lineColor: AppColors.colorf51a51,
                  ),
                  SizedBox(
                    height: 30,
                    width: 30,
                    child: loading ? CupertinoActivityIndicator() : null,
                  ),
                ],
              ),
            ),
          );
        } else {
          return NoConnectionScreen(
            onTap: () {
              Navigator.pushReplacement(
                context,
                FadeRoute(page: const SplashScreen()),
              );
            },
          );
        }
      },
    );
  }
}
