import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tangheem/api/user_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/ui/dialogs/general_dialog.dart';
import 'package:tangheem/widgets/login_textfield_widget.dart';

class ChangePasswordScreen extends StatefulWidget {
  static const String routeName = "/changePassword";

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

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

class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
  final TextEditingController _currentPasswordController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();

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

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

  void updatePassword(String email, String oldPassword, String password) async {
    Utils.showLoading(context);
    try {
      await UserApiClient().updatePassword(email, oldPassword, password);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
      return;
    } finally {
      Utils.hideLoading(context);
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove(GlobalConsts.userAuthData);
    AppState().setAuthenticationModel(null);
    await showDialog(
      context: context,
      barrierColor: Colors.white.withOpacity(0.2),
      builder: (BuildContext context) => GeneralDialog(
        message: "تم تغيير كلمة المرور بنجاح , الرجاء إعادة تسجيل الدخول من خلال الرابط المرسل إلى بريدك الإلكتروني",
        backgroundColor: Color(0xff598A8D),
      ),
    );
    Navigator.pop(context);
  }

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

    List<Widget> _actionsList = [
      "تغيير كلمة المرور".toText(20),
      24.height,
      LoginTextFieldWidget(hint: "كلمة المرور الحالية", controller: _currentPasswordController, iconData: Icons.lock_rounded, isPassword: true, isForChangePassword: true),
      10.height,
      LoginTextFieldWidget(hint: "كلمة المرور الجديدة", controller: _passwordController, iconData: Icons.lock_rounded, isForChangePassword: true),
      10.height,
      LoginTextFieldWidget(hint: "تأكيد كلمة المرور الجديدة", controller: _confirmPasswordController, iconData: Icons.lock_rounded, isPassword: true, isForChangePassword: true),
      16.height,
      Container(
        height: 45,
        // width: 165,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(32),
          border: Border.all(color: ColorConsts.brownLightColor, width: 2),
        ),
        child: "إعادة تعيين كلمة لمرور".toText(13),
      ).onPress(() {
        if (_currentPasswordController.text.length < 1) {
          Utils.showToast("يرجى إاخال كلمة المرور");
          return;
        }
        if (_passwordController.text.length < 1) {
          Utils.showToast("يرجى إاخال كلمة المرور");
          return;
        }
        if (_confirmPasswordController.text.length < 1) {
          Utils.showToast("يرجى تأكيد كلمة المرور");
          return;
        }
        if (_passwordController.text != _confirmPasswordController.text) {
          Utils.showToast("خطأ في تطابق كلمات المرور");
          return;
        }
        updatePassword(AppState().userEmail, _currentPasswordController.text, _passwordController.text);
      }),
    ];

    return SizedBox(
      width: double.infinity,
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          Image.asset(
            "assets/icons/new/home_dark.jpg",
            fit: BoxFit.cover,
            height: isPortrait ? double.infinity : null,
            width: isPortrait ? null : double.infinity,
            opacity: const AlwaysStoppedAnimation(1),
          ),
          Container(color: ColorConsts.darkText.withOpacity(0.8)),
          isPortrait
              ? Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    100.height,
                    Image.asset('assets/icons/new/Tangeem-logo-W.png', width: 50),
                    100.height,
                    Container(
                      width: 54,
                      height: 54,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: ColorConsts.dark2Text,
                      ),
                      child: SvgPicture.asset(
                        "assets/icons/new/user_acount.svg",
                        color: Colors.white,
                      ),
                    ),
                    14.height,
                    (AppState().userName ?? "").toText(18),
                    50.height,
                    ..._actionsList,
                  ],
                ).paddingOnly(left: 65, right: 65)
              : Row(
                  children: [
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 78,
                          height: 78,
                          decoration: BoxDecoration(shape: BoxShape.circle, color: ColorConsts.dark2Text),
                          child: SvgPicture.asset(
                            "assets/icons/new/user_acount.svg",
                            color: Colors.white,
                          ),
                        ),
                        14.height,
                        (AppState().userName ?? "").toText(25),
                      ],
                    ).expanded,
                    Column(mainAxisAlignment: MainAxisAlignment.center, children: _actionsList).expanded
                  ],
                ).paddingOnly(right: 65, left: 65),
        ],
      ),
    );
  }
}
