import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/login_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/input_widget.dart';

class NewPasswordScreen extends StatefulWidget {
  NewPasswordScreen({Key? key}) : super(key: key);

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

class _NewPasswordScreenState extends State<NewPasswordScreen> {
  TextEditingController password = TextEditingController();
  TextEditingController confirmPassword = TextEditingController();

  String? userName;

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

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

  void setNewPassword() async {
    Utils.showLoading(context);
    try {
      var genericResponseModel = await LoginApiClient().changePasswordForget(AppState().getForgetPasswordTokenID ?? "", password.text, confirmPassword.text, userName);
      Utils.hideLoading(context);
      Utils.showToast(LocaleKeys.passwordChangedSuccessfully.tr());
      Navigator.pop(context);
    } catch (ex) {
      print(ex);
      Utils.hideLoading(context);
      Utils.handleException(ex, context, (msg) {
        Utils.confirmDialog(context, msg);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    userName ??= ModalRoute.of(context)!.settings.arguments as String;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: MyColors.darkIconColor),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Column(
        children: [
          ListView(
            padding: const EdgeInsets.all(21),
            children: [
              LocaleKeys.setTheNewPassword.tr().toText24(isBold: true),
              LocaleKeys.typeYourNewPasswordBelow.tr().toText16(),
              16.height,
              InputWidget(
                LocaleKeys.password.tr(),
                "**********",
                password,
                onChange: (value) {
                  setState(() {});
                },
              ),
              12.height,
              InputWidget(
                LocaleKeys.confirmPassword.tr(),
                "**********",
                confirmPassword,
                isTextIsPassword: true,
                onChange: (value) {
                  setState(() {});
                },
              ),
              16.height,
              passwordConstraintsUI(LocaleKeys.doNotUseRecentPassword.tr(), true),
              8.height,
              passwordConstraintsUI(LocaleKeys.atLeastOneLowercase.tr(), checkRegEx(r'[a-z]')),
              // 8.height,
              // passwordConstraintsUI(LocaleKeys.atLeastOneUppercase.tr(), checkRegEx(r'[A-Z]')),
              8.height,
              passwordConstraintsUI(LocaleKeys.atLeastOneNumeric.tr(), checkRegEx(r'[0-9]')),
              8.height,
              passwordConstraintsUI(LocaleKeys.minimum8Characters.tr(), password.text.length >= 8),
              8.height,
              passwordConstraintsUI(LocaleKeys.doNotAddRepeatingLetters.tr(), checkRepeatedChars(password.text)),
              // 8.height,
              // passwordConstraintsUI(LocaleKeys.itShouldContainSpecialCharacter.tr(), checkRegEx(r'[!@#$%^&*(),.?":{}|<>]')),
              8.height,
              passwordConstraintsUI(LocaleKeys.confirmPasswordMustMatch.tr(), password.text.isNotEmpty && password.text == confirmPassword.text),
            ],
          ).expanded,
          DefaultButton(
                  LocaleKeys.update.tr(),
                  (!isPasswordCompliant(password.text, 8))
                      ? null
                      : () async {
                          setNewPassword();
                        })
              .insideContainer
        ],
      ),
    );
  }

  bool checkRegEx(String pattern) {
    return RegExp(pattern).hasMatch(password.text);
  }

  String recentPassword = "";

  bool checkRepeatedCharacters(String value) {
    if (value.isEmpty) {
      return false;
    }
    for (int i = 0; i < value.length; i++) {
      //if(i)
    }

    return true;
  }

  bool isPasswordCompliant(String? password, int minLength) {
    if (password == null || password.isEmpty) {
      return false;
    }

    // bool hasUppercase = password.contains(RegExp(r'[A-Z]'));
    bool hasDigits = password.contains(RegExp(r'[0-9]'));
    bool hasLowercase = password.contains(RegExp(r'[a-z]'));
    // bool hasSpecialCharacters = password.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]'));
    bool hasMinLength = password.length >= minLength;
    bool isMatched = password == confirmPassword.text;

    return hasDigits && hasLowercase && hasMinLength && isMatched && checkRepeatedChars(password);
  }

  bool checkRepeatedChars(String password) {
    bool isNonRepeatedLetters = true;
    if (password.length > 2) {
      for (int i = 0; i < password.length; i++) {
        String char = password[i];
        try {
          if (char == password[i + 1]) {
            isNonRepeatedLetters = false;
            break;
          }
        } catch (ex) {}
      }
    }
    return isNonRepeatedLetters;
  }

  Widget passwordConstraintsUI(String description, bool check) {
    return Row(
      children: [
        4.width,
        SizedBox(
          width: 12,
          height: 12,
          child: Checkbox(fillColor: MaterialStateProperty.all(MyColors.gradiantEndColor), shape: const CircleBorder(), value: check, onChanged: null),
        ),
        8.width,
        description.toText14()
      ],
    );
  }
}
