import 'dart:async';
import 'dart:convert';
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/models/customer-app-settings-model.dart';
import 'package:echo_app/models/language.dart';
import 'package:echo_app/screens/gest_user_page/guest_user.page.dart';
import 'package:echo_app/screens/login_page/login.page.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/screens/welcome.dart';
import 'package:echo_app/services/login.service.dart';
import 'package:echo_app/services/non-operator-service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get_utils/src/extensions/internacionalization.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../theme/variables.dart';
import 'no-connection.widget.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  NonOperatorService _nonOperatorService = new NonOperatorService();
  LoginService _loginService = new LoginService();
  bool isNoConnection = false;

  @override
  void initState() {
    super.initState();
    startTimer();
  }

  void startTimer() {
    //It will redirect  after 4 seconds
    Timer(Duration(seconds: 1), () async {
      // await Navigator.pushReplacement(
      //     context, MaterialPageRoute(builder: (context) => BackgroundTest()));
      navigateToNextPage();
    });
  }

  void navigateToNextPage() async {
    await getAllLanguages();
    if (!isNoConnection) {
      await _loginService.getLanguageId();
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? token = prefs.getString(ConstantStorage.tokenName);
      // get Gest Users Operators
      var response =
          await _nonOperatorService.getEchoGuestOpratorDataAndSettings();
      if (response['status'] == GlobalErrors.Success.index) {
        var data = response['data'];
        print(data);
        CoreSession.customerAppGestUserOperators =
            data['customerAppGestUserOperators'];
        // CoreSession.customerAppGestUserOperators.removeAt(0);
        CoreSession.customerAppGuestUserCaption =
            data['customerAppGuestUserCaption'];
        var settings = data['customerAppSettings'];

        prefs.setString(
            ConstantStorage.customerAppSettingsModel, json.encode(settings));
        CustomerAppSettingsModel.showAchievements =
            settings['showAchievements'];
        CustomerAppSettingsModel.showApplied = settings['showApplied'];
        CustomerAppSettingsModel.showOffers = settings['showOffers'];
        CustomerAppSettingsModel.showSummaryAfterSave =
            settings['showSummaryAfterSave'];
        CustomerAppSettingsModel.showCategoriesInHomePage =
            settings['showCategoriesInHomePage'];
        CustomerAppSettingsModel.showCategoryInItemScreen =
            settings['showCategoryInItemScreen'];
        CustomerAppSettingsModel.showDiscountDetailsInSummary =
            settings['showDiscountDetailsInSummary'];
        CustomerAppSettingsModel.showGroupInItemScreen =
            settings['showGroupInItemScreen'];
        // CustomerAppSettingsModel.showItemsDocument =
        //     settings['showItemsDocument'];
      }

      if (token == null || token == '') {
        if (response['status'] == GlobalErrors.Success.index &&
            CoreSession.customerAppGestUserOperators.length > 0) {
          CoreSession.guessUser = true;
          await Navigator.pushReplacement(context,
              MaterialPageRoute(builder: (context) => GuestUserPage()));
        } else {
          if (prefs.getString(ConstantStorage.username) != null) {
            var username = prefs.getString(ConstantStorage.username);
            var password = prefs.getString(ConstantStorage.password);
            var organizationId = prefs.getInt(ConstantStorage.organizationId);
              await _login(username, password, organizationId);
          }
          else{
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(
                builder: (context) => WelcomePage(),
              ), ModalRoute.withName("/")
            );
          }
        }
      } else {
        var username = prefs.getString(ConstantStorage.username);
        var password = prefs.getString(ConstantStorage.password);
        var organizationId = prefs.getInt(ConstantStorage.organizationId);
        await _login(username, password, organizationId);
      }
    } else {
      await Navigator.pushReplacement(context,
          MaterialPageRoute(builder: (context) => NoConnectionWidget()));
    }
  }

  getAllLanguages() async {
    var response = await _nonOperatorService.getAllLanguages();
    if (response == null) {
      isNoConnection = true;
    } else if (response['status'] == GlobalErrors.Success.index) {
      var languages = [];
      languages = response['data'];

      CoreSession.languages =
          List<Language>.from(languages.map((lang) => Language.fromJson(lang)));
    }
  }

  Future<void> _login(userName, password, organizationId) async {
    var response = await CoreSession.login(userName, password, organizationId);
    var result = response['result'];
    // var message = response['message'].toString();
    // var data = response['data'];
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var _weclcome = prefs.getBool(ConstantStorage.welcomed)?? false;

    if (result == GlobalErrors.Success.index) {
      Future.delayed(Duration(milliseconds: 5000), () {

        if (!_weclcome)
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => WelcomePage(),
            ),
          );
        else
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(
              builder: (context) => TapPage(),
            ),
          );
      });

    } else if (result == GlobalErrors.VersionNotMatch.index) {
      showDialog(
        context: context,
        builder: (_) => new AlertDialog(
          title: Text('message'.tr),
          content: new Text('new-version-found'.tr),
          actions: <Widget>[
            TextButton(
              child: Text('ok'.tr),
              onPressed: () {
                //Navigator.of(context).pop();
              },
            )
          ],
        ),
      );
    } else {
      EasyLoading.showError("error".tr);
    }
  }

  @override
  Widget build(BuildContext context) {
    return 
    Container(
        color: Variables.color_primary,
        child: Center(
          child: Image.asset(
            "assets/imgs/more_icons/splash.png",
            fit: BoxFit.fill,
          ),
        ));

    // Scaffold(
    //   body: Center(
    //     child: Container(
    //     decoration: BoxDecoration(
    //       image: DecorationImage(
    //         image: AssetImage("assets/images/bulb.jpg"),
    //         fit: BoxFit.cover,
    //       ),
    //     ),
    //     child: null /* add child content here */,
    //   ), //Image.asset("assets/imgs/loading.gif"),
    //   ),
    // );
  }
}
