import 'package:cherry_toast/cherry_toast.dart';
import 'package:cherry_toast/resources/arrays.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:initial_folder/providers/update_password_provider.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/login_regist/custom_text_form_field.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:initial_folder/providers/user_info_provider.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:provider/provider.dart';
import 'package:tap_debouncer/tap_debouncer.dart';

class SettingAkun extends StatefulWidget {
  @override
  State<SettingAkun> createState() => _SettingAkunState();
}

class _SettingAkunState extends State<SettingAkun> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final TextEditingController _currentPasswordController =
      TextEditingController(text: '');

  final TextEditingController _newPasswordController =
      TextEditingController(text: '');

  final TextEditingController _confirmPasswordController =
      TextEditingController(text: '');
  bool _isObscure = true;
  bool _isObscure1 = true;
  bool _isObscure2 = true;
  bool _isloading = true;

  @override
  Widget build(BuildContext context) {
    final Brightness brightnessValue =
        MediaQuery.of(context).platformBrightness;
    bool isDarkMode = brightnessValue == Brightness.dark;
    UserInfoProvider userInfoProvider = Provider.of<UserInfoProvider>(context);
    UpdatePasswordProvider updatePasswordProvider =
        Provider.of<UpdatePasswordProvider>(context);
    // EmailProvider emailProvider = Provider.of<EmailProvider>(context);
    // ShowHidePassword showHidePassword = Provider.of<ShowHidePassword>(context);
    // ShowHidePassword1 showHidePassword1 =
    //     Provider.of<ShowHidePassword1>(context);
    // ShowHidePassword2 showHidePassword2 =
    //     Provider.of<ShowHidePassword2>(context);

    Future _showMessage(String text) {
      return showDialog(
        context: context,
        builder: (context) => AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          backgroundColor: Colors.white,
          surfaceTintColor: Colors.transparent,
          contentPadding: EdgeInsets.fromLTRB(22, 30, 22, 30),
          content: Text(
            text,
            textAlign: TextAlign.center,
            style: thirdTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(12), letterSpacing: 1),
          ),
        ),
      );
    }

    updatePassword(
        {required idUser,
        String? email,
        String? oldPassword,
        String? password,
        String? newPasswordConfirm}) async {
      await Provider.of<UpdatePasswordProvider>(context, listen: false)
          .passwordUpdate(
              idUser: idUser,
              email: email,
              oldPassword: oldPassword,
              password: password,
              newPasswordConfirm: newPasswordConfirm)
          .then((value) => {
                setState(() {
                  if (value == true) {
                    _showMessage('Password Berhasil Diubah');
                    _isloading = true;
                  } else {
                    setState(() {
                      _isloading = true;
                      print('masuk sini');
                    });
                    _showMessage('Password Gagal Diubah');
                    _isloading = true;
                  }
                })
              });
    }

    void _validateInputs() async {
      setState(() {
        _isloading = false;
      });

      if (this._formKey.currentState!.validate()) {
        await updatePassword(
          idUser: userInfoProvider.result!.data[0].idUser,
          email: userInfoProvider.result!.data[0].email,
          oldPassword: _currentPasswordController.text,
          password: _newPasswordController.text,
          newPasswordConfirm: _confirmPasswordController.text,
        );
      } else {
        setState(() {
          _isloading = true;
          print('masuk sini');
        });
        CherryToast.error(
          toastPosition: Position.top,
          animationDuration: Durations.long1,
          title: Text(
            "Formulir tidak valid, periksa kembali",
            style: TextStyle(
              color: Colors.black,
              fontSize: 15,
            ),
          ),
          animationType: AnimationType.fromTop,
        ).show(context);
      }
    }

    Widget form() {
      Widget currentPasswordInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(2),
          controler: _currentPasswordController,
          hinttext: 'Masukkan password saat ini',
          title: 'Password Lama',
          obscuretext: _isObscure,
          validate: (String? value) {
            if (value!.length == 0)
              return 'Password tidak boleh kosong';
            else if (value.length < 8)
              return 'Password minimal harus berjumlah 8 karakter';

            return null;
          },
          suffix: GestureDetector(
              onTap: () => setState(() {
                    _isObscure = !_isObscure;
                  }),
              child: _isObscure
                  ? Icon(
                      Icons.visibility_off,
                      color: secondaryColor,
                      size: 18,
                    )
                  : Icon(
                      Icons.visibility,
                      color: secondaryColor,
                      size: 18,
                    )),
        );
      }

      Widget newPasswordInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(2),
          controler: _newPasswordController,
          hinttext: 'Masukkan password baru',
          title: 'Password Baru',
          obscuretext: _isObscure1,
          validate: (String? value) {
            if (value!.length == 0)
              return 'Password tidak boleh kosong';
            else if (value.length < 8)
              return 'Password minimal harus berjumlah 8 karakter';
            else if (value == _currentPasswordController.text) {
              return 'Password tidak boleh sama';
            }
            return null;
          },
          suffix: GestureDetector(
              onTap: () {
                setState(() {
                  _isObscure1 = !_isObscure1;
                });
              },
              child: _isObscure1
                  ? Icon(
                      Icons.visibility_off,
                      color: secondaryColor,
                      size: 18,
                    )
                  : Icon(
                      Icons.visibility,
                      color: secondaryColor,
                      size: 18,
                    )),
        );
      }

      Widget confirmPasswordInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(2),
          controler: _confirmPasswordController,
          hinttext: 'Konfirmasi password baru',
          title: 'Konfirmasi Password',
          obscuretext: _isObscure2,
          suffix: GestureDetector(
              onTap: () => setState(() {
                    _isObscure2 = !_isObscure2;
                  }),
              child: _isObscure2
                  ? Icon(
                      Icons.visibility_off,
                      color: secondaryColor,
                      size: 18,
                    )
                  : Icon(
                      Icons.visibility,
                      color: secondaryColor,
                      size: 18,
                    )),
          validate: (String? value) {
            if (value!.length == 0)
              return 'Password tidak boleh kosong';
            else if (value.length < 8)
              return 'Password minimal harus berjumlah 8 karakter';
            else if (value != _newPasswordController.text) {
              return 'Password baru dengan konfirmasi tidak sama';
            }
            return null;
          },
        );
      }

      Widget bottomNav() {
        return _isloading != true
            ? Container(
                margin: EdgeInsets.symmetric(
                    horizontal: getProportionateScreenWidth(45),
                    vertical: getProportionateScreenHeight(10)),
                child: LoadingButton(
                    backgroundButtonColor: primaryColor,
                    textButtonColor: Color(0xff050505)))
            : Container(
                margin: EdgeInsets.symmetric(
                    horizontal: getProportionateScreenWidth(45),
                    vertical: getProportionateScreenHeight(10)),
                child: TapDebouncer(
                  cooldown: const Duration(milliseconds: 3000),
                  onTap: () async =>
                      await {_validateInputs()}, // your tap handler moved here
                  builder: (BuildContext context, TapDebouncerFunc? onTap) {
                    return DefaultButton(
                      text: 'Simpan perubahan',
                      press: onTap,
                    );
                  },
                ),
              );
      }

      return Form(
        key: _formKey,
        child: Column(
          children: [
            currentPasswordInput(),
            SizedBox(height: getProportionateScreenHeight(15)),
            newPasswordInput(),
            SizedBox(height: getProportionateScreenHeight(15)),
            confirmPasswordInput(),
            SizedBox(height: getProportionateScreenHeight(70)),
            bottomNav(),
          ],
        ),
      );
    }

    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.background,
            centerTitle: true,
            title: Text(
              'Pengaturan Akun',
              style: secondaryTextStyle.copyWith(
                  letterSpacing: 0.23,
                  fontWeight: semiBold,
                  fontSize: getProportionateScreenWidth(14)),
            )),
        body: ListView(
          children: [
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  form(),
                  SizedBox(
                    height: getProportionateScreenHeight(13),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
