import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tangheem/api/authentication_api_client.dart';
import 'package:tangheem/app_state/app_state.dart';
import 'package:tangheem/classes/colors.dart';
import 'package:tangheem/classes/consts.dart';
import 'package:tangheem/classes/utils.dart';
import 'package:tangheem/extensions/int_extensions.dart';
import 'package:tangheem/extensions/string_extensions.dart';
import 'package:tangheem/extensions/widget_extensions.dart';
import 'package:tangheem/models/authentication_user_model.dart';
import 'package:tangheem/ui/screens/contact_us_screen.dart';
import 'package:tangheem/ui/screens/forgot_password_screen.dart';
import 'package:tangheem/ui/screens/registration_screen.dart';
import 'package:tangheem/widgets/login_textfield_widget.dart';

class LoginScreen extends StatefulWidget {
  static const String routeName = "/login";

  LoginScreen({Key key}) : super(key: key);

  @override
  _LoginScreenState createState() {
    return _LoginScreenState();
  }
}

class _LoginScreenState extends State<LoginScreen> {
  TextEditingController _emailController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  bool _isRemember = true;

  AuthenticationUserModel _authenticationUser;

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

  checkPrefs() {
    SharedPreferences.getInstance().then((value) {
      if ((value.getBool(GlobalConsts.isRememberMe) ?? false) == true) {
        _isRemember = true;
        _emailController.text = value.getString(GlobalConsts.email);
        _passwordController.text = value.getString(GlobalConsts.password);
      } else {
        _isRemember = false;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  void performLogin(String _email, String _password) async {
    Utils.showLoading(context);
    try {
      _authenticationUser = await AuthenticationApiClient().authenticateUser(_email, _password);

      SharedPreferences prefs = await SharedPreferences.getInstance();
      await prefs.setString(GlobalConsts.userAuthData, jsonEncode(_authenticationUser.toJson()));
      AppState().setAuthenticationModel(_authenticationUser);
      if (!_isRemember) {
        _email = "";
        _password = "";
      }
      await prefs.setBool(GlobalConsts.isRememberMe, _isRemember);
      await prefs.setString(GlobalConsts.email, _email);
      await prefs.setString(GlobalConsts.password, _password);
      Utils.showToast("تسجيل الدخول بنجاح");
      Utils.hideLoading(context);
      Navigator.pop(context);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;

    Widget _options = Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            InkWell(
              onTap: () {
                setState(() {
                  _isRemember = !_isRemember;
                });
              },
              child: Icon(_isRemember ? Icons.check_box_rounded : Icons.check_box_outline_blank_rounded, color: ColorConsts.borderDark2Text, size: 17),
              //child: SvgPicture.asset(_isAccept ? "assets/icons/checkOn.svg" : "assets/icons/checkOff.svg", width: 16, height: 16,color: ColorConsts.borderDarkText),
            ),
            10.width,
            "تذكرني".toText(14),
          ],
        ),
        "هل نسيت كلمة المرور؟".toText(14).onPress(() {
          Navigator.pushNamed(context, ForgotPasswordScreen.routeName);
        })
      ],
    );

    Widget _loginButton = SizedBox(
      width: double.infinity,
      height: isPortrait ? 50 : 45,
      child: TextButton(
        onPressed: () {
          if (_emailController.text.length < 1) {
            Utils.showToast("يرجى إدخال البريد الإلكتروني");
            return;
          } else if (!_emailController.text.isValidEmail()) {
            Utils.showToast("صيغة البريد الإلكتروني خاطئة");
            return;
          }
          if (_passwordController.text.length < 1) {
            Utils.showToast("يرجى إدخال كلمة المرور");
            return;
          }
          performLogin(_emailController.text, _passwordController.text);
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorConsts.brownLightColor,
          foregroundColor: Colors.white,
          textStyle: TextStyle(fontSize: 18),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
        ),
        child: Text("تسجيل الدخول"),
      ),
    );

    Widget _registrationButton = SizedBox(
      width: double.infinity,
      height: isPortrait ? 48 : 32,
      child: TextButton(
        onPressed: () {
          Navigator.pushNamed(context, RegistrationScreen.routeName);
        },
        style: TextButton.styleFrom(
          backgroundColor: Colors.transparent,
          foregroundColor: Colors.white,
          padding: EdgeInsets.zero,
          textStyle: TextStyle(fontSize: isPortrait ? 18 : 16),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0), side: BorderSide(color: Colors.white, width: 1)),
        ),
        child: Text("إنشاء حساب جديد"),
      ),
    );

    Widget _registrationText = Row(
      children: [
        Divider(height: 1, color: Colors.white).expanded,
        "ليس لديك حساب؟".toText(14).paddingOnly(left: 24, right: 24),
        Divider(height: 1, color: Colors.white).expanded,
      ],
    );

    return Scaffold(
      backgroundColor: ColorConsts.darkText,
      body: SafeArea(
        child: Directionality(
          textDirection: TextDirection.rtl,
          child: SingleChildScrollView(
            padding: EdgeInsets.only(top: isPortrait ? 140 : 40, bottom: 50, left: 40, right: 40),
            physics: BouncingScrollPhysics(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset("assets/icons/new/Tangeem-logo-W.png", width: isPortrait ? 136 : 100, height: 74),
                isPortrait ? 50.height : 0.height,
                "تسجيل الدخول".toText(isPortrait ? 18 : 20),
                32.height,
                if (isPortrait) ...[
                  LoginTextFieldWidget(hint: "البريد الإلكتروني", controller: _emailController, iconData: Icons.email_rounded),
                  20.height,
                  LoginTextFieldWidget(hint: "كلمة المرور", controller: _passwordController, iconData: Icons.lock_rounded, isPassword: true),
                  20.height,
                  _options,
                  20.height,
                  _loginButton,
                  20.height,
                  _registrationText,
                  20.height,
                  _registrationButton,
                  46.height,
                ] else ...[
                  Row(
                    children: [
                      Column(
                        children: [
                          LoginTextFieldWidget(hint: "البريد الإلكتروني", controller: _emailController, iconData: Icons.email_rounded),
                          20.height,
                          LoginTextFieldWidget(hint: "كلمة المرور", controller: _passwordController, iconData: Icons.lock_rounded, isPassword: true),
                        ],
                      ).expanded,
                      24.width,
                      Column(
                        children: [
                          _loginButton,
                          14.height,
                          _registrationText,
                          10.height,
                          _registrationButton,
                        ],
                      ).expanded
                    ],
                  ).paddingOnly(left: 42, right: 42),
                  16.height,
                  _options.paddingOnly(left: 42, right: 42),
                ],
                Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SvgPicture.asset("assets/icons/new/contact_us.svg", width: 26, height: 24, color: ColorConsts.greyC4Color),
                    8.height,
                    "اتصل بنا".toText(14, color: ColorConsts.greyC4Color),
                  ],
                ).onPress(() {
                  Navigator.pushNamed(context, ContactUsScreen.routeName);
                })
              ],
            ),
          ),
        ),
      ),
    );
  }
}
