import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../app/route.dart';
import '../change_password_screen/change_password_provider.dart';
import '/widget/snackbar_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../app/constant.dart';
import '../../provider/current_user_provider.dart';

class ChangePasswordScreen extends HookConsumerWidget {
  const ChangePasswordScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final currentPassword = useTextEditingController(text: "");
    final passwordNow = useTextEditingController(text: "");
    final confirmPassword = useTextEditingController(text: "");

    final hideCurrentPassword = useState(true);
    final hidePasswordNow = useState(true);
    final hideConfirmPassword = useState(true);

    final isLoading = useState<bool>(false);
    final userID = ref.watch(currentUserProvider)?.model.user?.mUserID ?? "0";

    ref.listen(ChangePasswordProvider, (previous, next) async {
      if (next is ChangePasswordStateLoading) {
        isLoading.value = true;
      } else if (next is ChangePasswordStateError) {
        isLoading.value = false;
        // print(next.message);
        SanckbarWidget(
            context, next.message, snackbarType.error);
      } else if (next is ChangePasswordStateDone) {
        isLoading.value = false;
        isLoading.value = false;
        if (next.model.status != "OK") {
          SanckbarWidget(context, "${next.model.message}", snackbarType.error);
        } else {
          final shared = await SharedPreferences.getInstance();
          final passwordSharePref = shared.getString("passwordX");
          if (passwordSharePref != null) {
            await shared.setString("passwordX", confirmPassword.text);
          }
          SanckbarWidget(
              context,
              "Berhasil Mengubah Password",
              snackbarType.success);
          Navigator.of(context).pushNamedAndRemoveUntil(
            menuRoute,
            (route) => false,
          );
        }
      }
    });

    disabledBtn<bool>() {
      if (currentPassword.text.isNotEmpty &&
          passwordNow.text.isNotEmpty &&
          confirmPassword.text.isNotEmpty &&
          (passwordNow.text == confirmPassword.text)) {
        return true;
      } else {
        return false;
      }
    }

    return Scaffold(
      bottomNavigationBar: Container(
        padding: EdgeInsets.symmetric(
            horizontal: Constant.getActualX(context: context, x: 35),
            vertical: Constant.getActualY(context: context, y: 40)),
        child: ElevatedButton(
            onPressed: () {
              // showDialog(
              //   context: context,
              //   builder: (context) {
              //     return ErrorDialog(
              //         title: "Something Went Wrong",
              //         message: "404 Not Found",
              //         showImage: true,
              //         showButton: true,
              //         buttonText: "Close",
              //         buttonFunction: () {
              //           print("a");
              //         });
              //   },
              // );
              if (currentPassword.text.isNotEmpty &&
                  passwordNow.text.isNotEmpty &&
                  confirmPassword.text.isNotEmpty &&
                  (passwordNow.text == confirmPassword.text)) {
                // print("a");

                ref.read(ChangePasswordProvider.notifier).ubahPassword(
                    userID: userID,
                    oldPassword: currentPassword.text,
                    newPassword: passwordNow.text);
              } else {
                // null;
                if (currentPassword.text.isEmpty) {
                  SanckbarWidget(
                      context,
                      "Password Saat ini tidak boleh kosong",
                      snackbarType.warning);
                } else {
                  if ((passwordNow.text.isEmpty ||
                      confirmPassword.text.isEmpty)) {
                    SanckbarWidget(
                        context,
                        "Password Saat ini atau Konformasi Password tidak boleh kosong",
                        snackbarType.warning);
                  } else {
                    if ((passwordNow.text != confirmPassword.text)) {
                      SanckbarWidget(
                          context,
                          "Konfirmasi Password & Password Baru harus sama",
                          snackbarType.warning);
                    }
                  }
                }
              }
            },
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                side: const BorderSide(width: 0.1, color: Colors.grey),
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: Container(
              height: Constant.getActualY(context: context, y: 46),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  Text(
                    "Simpan",
                    style: TextStyle(fontWeight: FontWeight.bold),
                  )
                ],
              ),
            )),
      ),
      body: ListView(
        children: [
          Container(
            height: Constant.getActualY(context: context, y: 56),
          ),
          Container(
            padding: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 10)),
            height: Constant.getActualY(context: context, y: 48),
            child: Row(
              children: [
                IconButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  icon: Icon(Icons.arrow_back_ios_rounded),
                ),
                Text(
                  "Ubah Password",
                  style: Constant.body1(context: context).copyWith(
                      fontWeight: FontWeight.w600, color: Constant.textPrimary),
                ),
              ],
            ),
          ),
          Container(
            height: Constant.getActualY(context: context, y: 31),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 34)),
            child: TextFormField(
              controller: currentPassword,
              obscureText: hideCurrentPassword.value,
              enableSuggestions: false,
              autocorrect: false,
              decoration: InputDecoration(
                suffixIcon: InkWell(
                    onTap: () {
                      hideCurrentPassword.value = !hideCurrentPassword.value;
                    },
                    child: Icon(!hideCurrentPassword.value
                        ? Icons.remove_red_eye
                        : Icons.remove_red_eye_outlined)),
                labelText: "Password Saat Ini",
                hintText: "Password Saat Ini",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
              ),
            ),
          ),
          Container(
            height: Constant.getActualY(context: context, y: 24),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 34)),
            child: TextFormField(
              controller: passwordNow,
              obscureText: hidePasswordNow.value,
              enableSuggestions: false,
              autocorrect: false,
              decoration: InputDecoration(
                suffixIcon: InkWell(
                    onTap: () {
                      hidePasswordNow.value = !hidePasswordNow.value;
                    },
                    child: Icon(!hidePasswordNow.value
                        ? Icons.remove_red_eye
                        : Icons.remove_red_eye_outlined)),
                labelText: "Password Baru",
                hintText: "Password Baru",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
              ),
            ),
          ),
          Container(
            height: Constant.getActualY(context: context, y: 24),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: Constant.getActualX(context: context, x: 34)),
            child: TextFormField(
              controller: confirmPassword,
              obscureText: hideConfirmPassword.value,
              enableSuggestions: false,
              autocorrect: false,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (value) {
                if (value != passwordNow.text) {
                  return "Konfirmasi password berbeda";
                }
              },
              onEditingComplete: () {
                FocusScope.of(context).unfocus();
              },
              // onChanged: (e) {
              //   if (e != passwordNow.text) {
              //     print("diff");
              //   }
              // },
              decoration: InputDecoration(
                suffixIcon: InkWell(
                    onTap: () {
                      hideConfirmPassword.value = !hideConfirmPassword.value;
                    },
                    child: Icon(!hideConfirmPassword.value
                        ? Icons.remove_red_eye
                        : Icons.remove_red_eye_outlined)),
                labelText: "konfirmasi Password Baru",
                hintText: "konfirmasi Password Baru",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
