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/string_extensions.dart';
import 'package:tangheem/models/authentication_user_model.dart';
import 'package:tangheem/ui/screens/forgot_password_screen.dart';
import 'package:tangheem/ui/screens/registration_screen.dart';
import 'package:tangheem/widgets/common_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) {
    return Scaffold(
      backgroundColor: ColorConsts.secondaryWhite,
      body: SafeArea(
        child: Directionality(
          textDirection: TextDirection.rtl,
          child: SingleChildScrollView(
            padding: EdgeInsets.all(32.0),
            physics: BouncingScrollPhysics(),
            child: Container(
              width: MediaQuery.of(context).size.width,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(8.0), color: Colors.white),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: 24, bottom: 24),
                    child: SvgPicture.asset("assets/logos/tangheem_logo.svg", width: 100, height: 100),
                  ),
                  Text(
                    "تسجيل الدخول",
                    style: TextStyle(fontSize: 22, color: ColorConsts.primaryBlue),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 16),
                    width: double.infinity,
                    padding: EdgeInsets.all(32.0),
                    color: ColorConsts.primaryBlue,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        CommonTextFieldWidget(hint: "البريد الإلكتروني", controller: _emailController, prefixIcon: "assets/icons/email.svg"),
                        SizedBox(height: 16),
                        CommonTextFieldWidget(hint: "كلمة المرور", controller: _passwordController, isPassword: true, prefixIcon: "assets/icons/password.svg"),
                        SizedBox(height: 16),
                        SizedBox(
                          width: double.infinity,
                          height: 50,
                          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(
                              primary: Colors.white,
                              backgroundColor: ColorConsts.secondaryPink,
                              textStyle: TextStyle(fontSize: 16, fontFamily: "DroidKufi"),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(6.0),
                              ),
                            ),
                            child: Text("تسجيل الدخول"),
                          ),
                        ),
                        SizedBox(height: 8),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(
                                  "تذكرني",
                                  style: TextStyle(color: Colors.white),
                                ),
                                SizedBox(width: 8),
                                InkWell(
                                    onTap: () {
                                      setState(() {
                                        _isRemember = !_isRemember;
                                      });
                                    },
                                    child: SvgPicture.asset(_isRemember ? "assets/icons/checkOn.svg" : "assets/icons/checkOff.svg", width: 16, height: 16))
                              ],
                            ),
                            InkWell(
                              onTap: () {
                                Navigator.pushNamed(context, ForgotPasswordScreen.routeName);
                              },
                              child: Text(
                                "نسيت كلمة المرور؟",
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Navigator.pushNamed(context, RegistrationScreen.routeName);
                    },
                    child: Container(
                      height: 50,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: ColorConsts.tertiaryPurple,
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(8),
                          bottomRight: Radius.circular(8),
                        ),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            " حساب جديد",
                            style: TextStyle(fontSize: 14, color: Colors.white),
                          ),
                          Icon(Icons.arrow_forward_ios, color: Colors.white, size: 12),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
