import 'dart:convert';

import 'package:community_material_icon/community_material_icon.dart';
import 'package:echo_app/auth/auth-request.dart';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/app-properties.dart';
import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/screens/login_page/login.page.dart';
import 'package:echo_app/widgets/languages/languages_dropdown.widget.dart';
import 'package:echo_app/screens/sign_up/sign_up.page.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../theme/variables.dart';

// ignore: must_be_immutable
class GuestUserPage extends StatefulWidget {
  List<TextLanguage> orginazationsList = [];
  String orgCaption = '';
  bool showLoginAsGuest = false;
  @override
  State<GuestUserPage> createState() => _GuestUserPageState();
  GuestUserPage() {
    int languageId = CoreSession.selectedLanguageId;
    CoreSession.customerAppGestUserOperators.forEach((element) {
      if (element['languages'] != null && element['languages'].length > 0) {
        var list = [];
        list = element['languages'];
        var listInLngId = list
            .map((e) => new TextLanguage(e['organizationId'], e['languageId'],
                e['description'], e['imageName']))
            .where((element) => element.languageId == languageId)
            .toList();

        orginazationsList.addAll(listInLngId);
      }
    });
    if (CoreSession.customerAppGestUserOperators.length > 0 &&
        CoreSession.customerAppGestUserOperators.length == 1) {
      showLoginAsGuest = true;
    }
    if (CoreSession.customerAppGuestUserCaption.length > 0)
      orgCaption = CoreSession.customerAppGuestUserCaption.firstWhere(
        (element) => element['languageId'] == languageId)['description'];
  }
}

class _GuestUserPageState extends State<GuestUserPage> {
  var constPadding = EdgeInsets.all(0);
  int dropdownValue = 1;
  var userName = '';
  var password = '';
  var organizationId = -1;
  var appVersion;
  var auth = new Auth();

  Future<void> onChangeValue(orgId) async {
    print(orgId);
    var operator;
    int index = CoreSession.customerAppGestUserOperators
        .indexWhere((op) => op['organizationId'] == orgId);
    if (index > -1) {
      operator = CoreSession.customerAppGestUserOperators[index];
      userName = operator['operatorName'];
      password = operator['operatorPassword'];
      organizationId =  operator['organizationId'];
    }
  }

  void _login() async {
    if (userName == '' || password == '') {
      Alert(
        context: context,
        type: AlertType.error,
        useRootNavigator: true,
        title: "message".tr,
        desc: "msg-select-organization".tr,
        buttons: [
          DialogButton(
            color: Colors.white,
            child: Text(
              "ok".tr,
              style: TextStyle(color: Colors.green, fontSize: 20),
            ),
            onPressed: () => {
              Navigator.of(context, rootNavigator: true).pop(),
            },
            width: 120,
          )
        ],
      ).show();
    } else {
      var response =
          await CoreSession.login(userName, password, organizationId);
      var result = response['result'];
      if (result == GlobalErrors.Success.index) {
        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);
      }
    }
  }

  _loginAsGestUser() async {
    var savedBasket = [];
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? orderBasketJson = prefs.getString(ConstantStorage.orderBasket);
    if (orderBasketJson != null) {
      savedBasket = json.decode(orderBasketJson);
    } else {
      savedBasket = [];
    }

    int index = -1;
    // ignore: unnecessary_null_comparison
    if (savedBasket != null && savedBasket.length > 0) {
      // change Gest user (change org)
      if (CoreSession.currentOperator != null) {
        index = savedBasket.indexWhere((element) =>
            element['customerId'] ==
                CoreSession.currentOperator['customerId'] &&
            element['outletId'] == CoreSession.currentOperator['outletId']);
      }
    }
    // ignore: unnecessary_null_comparison
    if (CoreSession.ordersBasket != null &&
        CoreSession.ordersBasket.length > 0) {
      var items = [];
      items = CoreSession.currentBasket['items'];
      if (items.length > 0) {
        Alert(
          useRootNavigator: true,
          context: context,
          type: AlertType.info,
          title: "confirm".tr,
          desc: "change-org-confirm".tr,
          buttons: [
            DialogButton(
              color: Colors.white,
              child: Text(
                "yes".tr,
                style: TextStyle(color: Colors.greenAccent, fontSize: 20),
              ),
              onPressed: () => {
                if (index > -1)
                  {
                    savedBasket.removeAt(index),
                    prefs.setString(
                        ConstantStorage.orderBasket, json.encode(savedBasket)),
                    _login(),
                    Navigator.of(context, rootNavigator: true).pop(),
                  },
              },
              width: 120,
            ),
            DialogButton(
              color: Colors.white,
              child: Text(
                "no".tr,
                style: TextStyle(color: Colors.red, fontSize: 20),
              ),
              onPressed: () => {
                Navigator.of(context, rootNavigator: true).pop(),
              },
              width: 120,
            )
          ],
        ).show();
      } else {
        if (index > -1) {
          savedBasket.removeAt(index);
          prefs.setString(
              ConstantStorage.orderBasket, json.encode(savedBasket));
        }
        _login();
      }
    } else {
      if (index > -1) {
        savedBasket.removeAt(index);
        prefs.setString(ConstantStorage.orderBasket, json.encode(savedBasket));
      }
      _login();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 40),
          child: Column(
            children: <Widget>[
              Expanded(
                flex: 10,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (!this.widget.showLoginAsGuest)
                      Text(
                          this.widget.orgCaption == ''
                              ? "msg-select-organization".tr
                              : this.widget.orgCaption,
                          style: TextStyle(color: Colors.black, fontSize: 18)),
                    if (!this.widget.showLoginAsGuest)
                      DropdownButtonHideUnderline(
                        child: DropdownButtonFormField<dynamic>(
                          isExpanded: true,
                          style: TextStyle(color: Colors.black, fontSize: 15),
                          decoration: InputDecoration(
                            enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                                  color: Variables.color_primary),
                            ),
                          ),
                          onChanged: (val) {
                            // this.dropdownValue = val;

                            this.onChangeValue(val);
                          },
                          hint: Text("select".tr),
                          items: this
                              .widget
                              .orginazationsList
                              .map<DropdownMenuItem>((item) {
                            return DropdownMenuItem(
                              value: item.id,
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  new Image.asset(
                                    "assets/imgs/countries/${item.imageName}.png",
                                    fit: BoxFit.fitWidth,
                                    width:
                                        MediaQuery.of(context).size.width / 12,
                                  ),
                                  SizedBox(width: 10),
                                  new Text(item.description),
                                ],
                              ),
                            );
                          }).toList(),
                        ),
                      ),
                    if (this.widget.showLoginAsGuest)
                      TextButton(
                        onPressed: () {
                          var operator =
                              CoreSession.customerAppGestUserOperators[0];
                          userName = operator['operatorName'];
                          password = operator['operatorPassword'];
                          _login();
                        },
                        child: Text("continue-guest-user".tr),
                      ),
                    if (!this.widget.showLoginAsGuest) SizedBox(height: 20),
                    if (!this.widget.showLoginAsGuest)
                      TextButton(
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.white, backgroundColor: Variables.color_primary,
                          padding: EdgeInsets.symmetric(horizontal: 10),
                        ),
                        onPressed: () {
                          _loginAsGestUser();
                        },
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text("go".tr),
                            CoreSession.selectedLanguageId != 2
                                ? Icon(CommunityMaterialIcons.arrow_right)
                                : Icon(CommunityMaterialIcons.arrow_left),
                          ],
                        ),
                      ),
                    SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "msg-have-account".tr,
                          style: TextStyle(color: Colors.black, fontSize: 15),
                        ),
                        TextButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => LoginPage(),
                              ),
                            );
                          },
                          child: Text("login-small".tr),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "msg-new-user".tr,
                          style: TextStyle(color: Colors.black, fontSize: 15),
                        ),
                        TextButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => SignUpPage(),
                              ),
                            );
                          },
                          child: Text("create-account".tr),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1,
                child: LanguagesDropdownWidget(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
