import 'dart:async';

import 'package:app_petty_cash/app/constant.dart';
import 'package:app_petty_cash/provider/current_menu_provider.dart';
import 'package:app_petty_cash/screen/change_pasword/change_password_provider.dart';
import 'package:app_petty_cash/screen/login/logout_provider.dart';
import 'package:app_petty_cash/widget/custom_drawer.dart';
import 'package:app_petty_cash/widget/sankbar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedUser = ref.read(currentUserProvider);
    //menampung user token jika ada
    final userToken = ref.read(currentUserProvider)?.token ?? "";
    final userID = ref.read(currentUserProvider)?.model.M_UserID ?? "0";

    final isLoading = useState(false);
    final ctrlOldPassword = useTextEditingController(text: "");
    final ctrlNewPassword = useTextEditingController(text: "");
    final ctrlConfirmPassword = useTextEditingController(text: "");
    final loading = useState(false);

    // inisialisasi agar bisa cek apakah user sudah login sukses apa belum
    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final userID = ref.read(currentUserProvider)?.model.M_UserID ?? "0";
        if (userID == "0") {
          //not login
          Navigator.of(context)
              .pushNamedAndRemoveUntil(loginRoute, (route) => true);

          //  Navigator.popAndPushNamed(context, loginRoute);
          return;
        }
      });
      return () {};
    }, []);
    Logout() async {
      final shared = await SharedPreferences.getInstance();
      final bearerString = shared.get(Constant.bearerName).toString();
      // print(bearerString);
      if (bearerString.isNotEmpty) {
        shared.remove(bearerString);
        shared.clear();
        // Navigator.popAndPushNamed(context, loginRoute);
        ref.read(currentUserProvider.notifier).state = null;
        Navigator.of(context)
            .pushNamedAndRemoveUntil(loginRoute, (route) => false);
      }
    }

    // read provider home
    ref.listen(
      ChangePasswordProvider,
      (previous, next) {
        if (next is ChangePasswordStateLoading) {
          loading.value = true;
        } else if (next is ChangePasswordStateError) {
          loading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is ChangePasswordStateDone) {
          loading.value = false;
          SanckbarWidget(
            context,
            "Ubah Password Berhasil!\nSilahkan Login dengan password baru",
            snackbarType.success,
          );
          Logout();
        }
      },
    );

    return Padding(
      padding: EdgeInsets.only(
          top: Constant.getActualYPhone(context: context, y: 30)),
      child: Scaffold(
        appBar: AppBar(
          //  centerTitle: true,
          title: Text(
            'Change Password',
            style: TextStyle(color: Constant.textWhite),
          ),
          backgroundColor: Constant.pcBtnBackgroundColor,
          iconTheme: IconThemeData(
            color: Constant.textWhite,
          ),
        ),
        drawer: CustomDrawer(),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Container(
              width: Constant.getActualXPhone(context: context, x: 390),
              height: Constant.getActualYPhone(context: context, y: 844),
              child: Column(
                children: [
                  //Old Password
                  // inputan email
                  Padding(
                    padding: EdgeInsets.only(
                      // top: Constant.getActualYPhone(context: context, y: 63),
                      left: Constant.getActualXPhone(context: context, x: 20),
                      right: Constant.getActualXPhone(context: context, x: 20),
                    ),
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'Old Password',
                        style: Constant.body1_400_dibulan(context: context)
                            .copyWith(
                                fontWeight: FontWeight.w600,
                                color: Constant.textBlack),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: Constant.getActualYPhone(context: context, y: 4),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                      top: Constant.getActualYPhone(context: context, y: 5),
                      left: Constant.getActualXPhone(context: context, x: 20),
                      right: Constant.getActualXPhone(context: context, x: 20),
                    ),
                    child: TextField(
                      readOnly: loading.value,
                      controller: ctrlOldPassword,
                      obscureText: false,
                      decoration: InputDecoration(
                        hintStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        labelStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Constant.textGreyv2,
                            width: 1,
                          ),
                        ),
                        labelText: "Your Old Password",
                        hintText: 'Input Your Old Password',
                      ),
                    ),
                  ),
                  SizedBox(
                    height: Constant.getActualYPhone(context: context, y: 40),
                  ),
                  //New password
                  Padding(
                    padding: EdgeInsets.only(
                      // top: Constant.getActualYPhone(context: context, y: 63),
                      left: Constant.getActualXPhone(context: context, x: 20),
                      right: Constant.getActualXPhone(context: context, x: 20),
                    ),
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'New Password',
                        style: Constant.body1_400_dibulan(context: context)
                            .copyWith(
                                fontWeight: FontWeight.w600,
                                color: Constant.textBlack),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: Constant.getActualYPhone(context: context, y: 4),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                      top: Constant.getActualYPhone(context: context, y: 5),
                      left: Constant.getActualXPhone(context: context, x: 20),
                      right: Constant.getActualXPhone(context: context, x: 20),
                    ),
                    child: TextField(
                      readOnly: loading.value,
                      controller: ctrlNewPassword,
                      obscureText: false,
                      decoration: InputDecoration(
                        hintStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        labelStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Constant.textGreyv2,
                            width: 1,
                          ),
                        ),
                        labelText: "Your New Password",
                        hintText: 'Input Your New Password',
                      ),
                    ),
                  ),
                  SizedBox(
                    height: Constant.getActualYPhone(context: context, y: 40),
                  ),
                  //Confirm Password
                  Padding(
                    padding: EdgeInsets.only(
                      // top: Constant.getActualYPhone(context: context, y: 63),
                      left: Constant.getActualXPhone(context: context, x: 20),
                      right: Constant.getActualXPhone(context: context, x: 20),
                    ),
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'Confirm Password',
                        style: Constant.body1_400_dibulan(context: context)
                            .copyWith(
                                fontWeight: FontWeight.w600,
                                color: Constant.textBlack),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: Constant.getActualYPhone(context: context, y: 4),
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                      top: Constant.getActualYPhone(context: context, y: 5),
                      left: Constant.getActualXPhone(context: context, x: 20),
                      right: Constant.getActualXPhone(context: context, x: 20),
                    ),
                    child: TextField(
                      readOnly: loading.value,
                      controller: ctrlConfirmPassword,
                      obscureText: false,
                      decoration: InputDecoration(
                        hintStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        labelStyle:
                            Constant.body2_400(context: context).copyWith(
                          color: Constant.textGreyv2,
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Constant.textGreyv2,
                            width: 1,
                          ),
                        ),
                        labelText: "Your Confirm Password",
                        hintText: 'Input Your Confirm Password',
                      ),
                    ),
                  ),

                  SizedBox(
                    height: Constant.getActualYPhone(context: context, y: 40),
                  ),
                  //Button Update Password
                  Padding(
                    padding: EdgeInsets.only(
                      left: Constant.getActualXPhone(context: context, x: 20),
                      right: Constant.getActualXPhone(context: context, x: 20),
                    ),
                    child: SizedBox(
                      width: Constant.getActualXPhone(context: context, x: 390),
                      height: Constant.getActualYPhone(context: context, y: 50),
                      child: ElevatedButton(
                        // onPressed: () {
                        //   Navigator.of(context).pushNamed(homeRoute);
                        // },
                        onPressed: (loading.value == true)
                            ? null
                            : () {
                                if (ctrlNewPassword.text !=
                                    ctrlConfirmPassword.text) {
                                  SanckbarWidget(
                                      context,
                                      'New Password dan dan confirm password tidak sama!',
                                      snackbarType.warning);
                                  return;
                                }
                                if (ctrlOldPassword.text ==
                                    ctrlConfirmPassword.text) {
                                  SanckbarWidget(
                                      context,
                                      'Password lama dan baru tidak boleh sama',
                                      snackbarType.warning);
                                  return;
                                }
                                if (ctrlOldPassword.text.isEmpty ||
                                    ctrlNewPassword.text.isEmpty ||
                                    ctrlConfirmPassword.text.isEmpty) {
                                  isLoading.value = true;
                                  SanckbarWidget(context, 'Inputan harus diisi',
                                      snackbarType.warning);
                                } else {
                                  ref
                                      .read(ChangePasswordProvider.notifier)
                                      .postChangePassword(
                                        userToken: userToken,
                                        userID: userID,
                                        oldPassword: ctrlOldPassword.text,
                                        newPassword: ctrlNewPassword.text,
                                        confirmPassword:
                                            ctrlConfirmPassword.text,
                                      );
                                }
                              },
                        style: ButtonStyle(
                          backgroundColor: MaterialStateColor.resolveWith(
                              (st) => (loading.value == true)
                                  ? Constant.textGrey
                                  : Constant.pcBtnBackgroundColor),
                          shape:
                              MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                              side: BorderSide(
                                color: Constant.pcBtnBackgroundColor,
                              ),
                            ),
                          ),
                          shadowColor:
                              MaterialStateProperty.all(Color(0xffff48423d)),
                          elevation: MaterialStateProperty.all(4.0),
                        ),

                        child: Stack(
                          children: [
                            (isLoading.value)
                                ? SizedBox(
                                    width: Constant.getActualXPhone(
                                        context: context, x: 24),
                                    height: Constant.getActualYPhone(
                                        context: context, y: 32),
                                    child: Center(
                                      child: CircularProgressIndicator(
                                        color: Colors.white,
                                      ),
                                    ),
                                  )
                                : Align(
                                    alignment: Alignment.center,
                                    child: Text(
                                      'Submit',
                                      style: Constant.titleH3_700(
                                              context: context)
                                          .copyWith(
                                              color: Constant.textLoginColor),
                                    ),
                                  ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
