import 'dart:async';

import 'package:echo_app/auth/auth-request.dart';
import 'package:echo_app/enums/global-errors.dart';
import 'package:echo_app/models/constant-storage.dart';
import 'package:echo_app/models/operator.dart';
import 'package:echo_app/screens/gest_user_page/guest_user.page.dart';
import 'package:echo_app/screens/login_page/widgets/guset_user.dart';
import 'package:echo_app/screens/vendors-list/vendors-list.page.dart';
import 'package:echo_app/screens/welcome.dart';
import 'package:echo_app/theme/variables.dart';
import 'package:echo_app/widgets/languages/languages_dropdown.widget.dart';
import 'package:flutter_otp_text_field/flutter_otp_text_field.dart';
import 'package:echo_app/screens/login_page/widgets/signin_button.dart';
import 'package:echo_app/screens/login_page/widgets/signup_button.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:echo_app/widgets/general_text_form_field.widget.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:geolocator/geolocator.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

// ignore: must_be_immutable
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;

  Future<bool> _handlePermission() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await _geolocatorPlatform.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return false;
    }

    // permission = await _geolocatorPlatform.checkPermission();
    // if (permission == LocationPermission.denied) {
    //   permission = await _geolocatorPlatform.requestPermission();
    //   if (permission == LocationPermission.denied) {
    //     return false;
    //   }
    // }
    //
    // if (permission == LocationPermission.deniedForever) {
    //   return false;
    // }

    return true;
  }

  //Style
  var textFieldLableStyle = TextStyle(color: Colors.green);
  var textFieldBorder = UnderlineInputBorder(
    borderSide: BorderSide(color: Colors.green),
  );

  //End Style

  TextEditingController userNameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  //OperatorForLogin operator = new OperatorForLogin();
  OperatorModel oeratorModel = new OperatorModel();
  var userNamePadding = EdgeInsets.fromLTRB(0, 0, 0, 10);
  var passwordPadding = EdgeInsets.fromLTRB(0, 0, 0, 0);
  var auth = new Auth();
  final _form = GlobalKey<FormState>();
  final _passwordFocusNode = FocusNode();
  String msg = '';
  bool loading = false;
  var OTPFilled = '';

  Timer? _timer;
  int _start = 120; // 2 minutes in seconds

  void _login(userName, password, organizationId) async {
    loading = true;
    if (userName.isEmpty && password.isNotEmpty) {
      msg = 'enter-username';
      loading = false;
      setState(() {});
      return;
    }

    if (userName.isNotEmpty && password.isEmpty) {
      msg = 'enter-password';
      loading = false;
      setState(() {});
      return;
    }

    if (userName.isEmpty && password.isEmpty) {
      msg = 'enter-username-password';
      loading = false;
      return;
    }

    EasyLoading.show(status: 'loading'.tr);
    var response = await CoreSession.login(userName, password, organizationId);

    var result = response['result'];
    var message = response['message'];
    // ignore: unrelated_type_equality_checks

    SharedPreferences prefs = await SharedPreferences.getInstance();
    var _weclcome = prefs.getBool(ConstantStorage.welcomed) ?? false;

    if (response['result'] == GlobalErrors.Success.index) {
      loading = false;
      EasyLoading.dismiss();
      const oneSec = Duration(seconds: 1);
      showModalBottomSheet<void>(
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.circular(20.0),
          ),
        ),
        builder: (BuildContext context) {
          return FractionallySizedBox(
            heightFactor: 0.8,
            child: StatefulBuilder(
              builder: (BuildContext context,
                  void Function(void Function()) setState) {
                if (_start == 120)
                  _timer = Timer.periodic(oneSec, (Timer timer) {
                    if (_start == 0) {
                      timer.cancel();
                      setState(() {});
                    } else {
                      _start--;
                      setState(() {});
                    }
                  });
                return Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Scaffold(
                    resizeToAvoidBottomInset: true,
                    body: Container(
                      height: MediaQuery.of(context).size.height * 0.4,
                      child: Center(
                        child: SingleChildScrollView(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              const Text(
                                'OTP',
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 20,
                                    fontWeight: FontWeight.bold),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                              Container(
                                  child: Column(
                                children: [
                                  const Text(
                                    'Welcome to Echo!\nWe send you a code to confirm login on \n',
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 14),
                                  ),
                                  Text(
                                    '\nSupport@e-incube.com',
                                    style: TextStyle(
                                        color: Variables.color_primary, fontSize: 14),
                                  )
                                ],
                              )),
                              SizedBox(
                                height: 50,
                              ),
                              OtpTextField(
                                cursorColor: Variables.color_primary,
                                fillColor: Variables.color_primary,
                                numberOfFields: 4,
                                borderColor: Variables.color_primary,
                                //set to true to show as box or false to show as dash
                                showFieldAsBox: true,
                                //runs when a code is typed in
                                onCodeChanged: (String code) {
                                  //handle validation or checks here
                                },
                                //runs when every textfield is filled
                                onSubmit: (String verificationCode) {
                                  OTPFilled = verificationCode;
                                }, // end onSubmit
                              ),
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                    vertical: 8.0, horizontal: 10),
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      backgroundColor: Variables.color_primary,
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 20, vertical: 5),
                                      textStyle: TextStyle(
                                          fontSize: 14,
                                          fontWeight: FontWeight.bold)),
                                  child: Row(
                                    children: [
                                      Spacer(),
                                      Text('confirm'.tr),
                                      Spacer(),
                                    ],
                                  ),
                                  onPressed: () {
                                    _timer?.cancel();
                                    _start = 120;
                                    if (OTPFilled != '0000') {
                                      showDialog(
                                          context: context,
                                          builder: (context) {
                                            return AlertDialog(
                                              title: Text("Verification Code"),
                                              content: Text(
                                                  'Code entered not valid'),
                                            );
                                          });
                                    } else if (!_weclcome)
                                      Navigator.pushReplacement(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => WelcomePage(),
                                        ),
                                      );
                                    else
                                      Navigator.pushReplacement(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => TapPage(),
                                        ),
                                      );
                                  },
                                ),
                              ),
                              Row(
                                children: [
                                  SizedBox(
                                    width: 50,
                                  ),
                                  Text(
                                    "${_start ~/ 60}:${(_start % 60).toString().padLeft(2, '0')}",
                                    style: TextStyle(
                                        fontSize: 14, color: Colors.grey),
                                  ),
                                  Spacer(),
                                  InkWell(
                                      onTap: () {
                                        if (_start == 0) {
                                          _start = 120;
                                          showDialog(
                                              context: context,
                                              builder: (context) {
                                                return AlertDialog(
                                                  title:
                                                      Text("Verification Code"),
                                                  content: Text(
                                                      'The code has been sent to your email.'),
                                                );
                                              });
                                          setState(() {});
                                        } else {
                                          showDialog(
                                              context: context,
                                              builder: (context) {
                                                return AlertDialog(
                                                  title:
                                                      Text("Verification Code"),
                                                  content: Text(
                                                      'Need wait timer to end'),
                                                );
                                              });
                                        }
                                      },
                                      child: Text("Resend the code",
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.grey))),
                                  SizedBox(
                                    width: 20,
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      );
    } else if (response['result'] ==
        GlobalErrors.EchoCustomerMultiAccount.index) {
      loading = false;
      EasyLoading.dismiss();
      CoreSession.organizationList = response['data']['organizationsList'];
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => VendorsList(userName, password),
        ),
      );
    } else if (result == GlobalErrors.VersionNotMatch.index) {
      loading = false;
      EasyLoading.dismiss();
      Alert(
        context: context,
        type: AlertType.error,
        useRootNavigator: true,
        title: "message".tr,
        desc: "new-version-found".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 {
      setState(() {
        loading = false;
        this.msg = message;
        EasyLoading.dismiss();
      });
    }
  }

  void _loginAsGuest() async {
    if (CoreSession.customerAppGestUserOperators.length > 0) {
      if (CoreSession.customerAppGestUserOperators.length == 1) {
        var operator = CoreSession.customerAppGestUserOperators[0];
        final userName = operator['operatorName'];
        final password = operator['operatorPassword'];
        final organizationId = operator['organizationId'];
        _login(userName, password, organizationId);
      } else {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => GuestUserPage(),
          ),
        );
      }
    }
  }

  _onSubmitUsernme() {
    FocusScope.of(context).requestFocus(_passwordFocusNode);
  }

  _onSubmitPassword() {
    if (!loading) {
      final userName = userNameController.text;
      final password = passwordController.text;
      _login(userName, password, -1);
    }
  }

  _openSignup() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SignUpPage(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final hasPermission = _handlePermission();

    final mediaQuery = MediaQuery.of(context);
    return SafeArea(
      child: WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Scaffold(
          bottomSheet: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Spacer(),
                LanguagesDropdownWidget(),
                Spacer(),
              ],
            ),
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                height: (mediaQuery.size.height -
                        mediaQuery.padding.top -
                        mediaQuery.padding.bottom) *
                    0.8,
                child: Column(
                  children: [
                    SizedBox(
                      height: 120,
                    ),
                    Row(
                      children: [
                        SizedBox(
                          width: 20,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text(
                              "Welcome-Back".tr,
                              style: TextStyle(
                                  fontSize: 24, fontWeight: FontWeight.bold),
                            ),
                            Text(
                              "Welcome-Info".tr,
                              style:
                                  TextStyle(fontSize: 14, color: Colors.grey),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 35),
                      child: Form(
                        key: _form,
                        child: Column(
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(top: 5),
                              child: Text(
                                msg.tr,
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  color: Colors.redAccent,
                                ),
                              ),
                            ),
                            Container(
                              child: GeneralTextFormFieldWidget(
                                  'username',
                                  userNameController,
                                  false,
                                  '',
                                  true,
                                  false,
                                  null,
                                  _onSubmitUsernme,
                                  null,
                                  this.userNamePadding,
                                  null,
                                  1,
                                  false,
                                  false,
                                  false,
                                  15,
                                  TextInputType.text),
                            ),
                            SizedBox(
                              height: 5,
                            ),
                            Container(
                              child: GeneralTextFormFieldWidget(
                                  'password',
                                  passwordController,
                                  false,
                                  '',
                                  true,
                                  true,
                                  null,
                                  _onSubmitPassword,
                                  null,
                                  this.passwordPadding,
                                  _passwordFocusNode,
                                  1,
                                  false,
                                  false,
                                  false,
                                  15,
                                  TextInputType.text),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: SignInButton(this._onSubmitPassword, loading),
                    ),
                    SignUpButton(_openSignup),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
