import React, { useEffect, useState } from "react";
import Orange_Btn from "../../common_btn/orange_btn/Orange_Btn";
import { Form, Modal } from "react-bootstrap";
import { useForm } from "react-hook-form";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
import PasswordChecklist from "react-password-checklist";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Gray_Btn from "../../common_btn/gray_btn/Gray_Btn";
import Green_btn from "../../common_btn/green_btn/Green_btn";
import "./Set_New_Password_Modal.css";
import { useDispatch, useSelector } from "react-redux";
import { forgotPassword } from "../../../../features/auth/authSlice";
import { appSetup } from "../../../../features/master/masterSlice";
import Black_Btn from "../../common_btn/black_btn/Black_Btn";

const Set_New_Password_Modal = ({
  email,
  contact,
  setEmail,
  setContact,
  ...props
}) => {
  const {
    control,
    register,
    setError,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const [password, setPassword] = useState("");
  const [passwordAgain, setPasswordAgain] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showPasswordOne, setShowPasswordOne] = useState(false);
  const [iconOne, setIconOne] = useState(faEyeSlash);
  const [iconTwo, setIconTwo] = useState(faEyeSlash);

  const togglePasswordVisibility = (field) => {
    if (field === "password") {
      setShowPassword(!showPassword);
      setIconOne(showPassword ? faEyeSlash : faEye);
    } else if (field === "reenterPassword") {
      setShowPasswordOne(!showPasswordOne);
      setIconTwo(showPasswordOne ? faEyeSlash : faEye);
    }
  };

  const dispatch = useDispatch();

  const onSubmit = async (d) => {
    const data = {
      email: email,
      contact_no: contact,
      password: d?.password,
    };
    const verify = await dispatch(forgotPassword(data));

    if (verify.meta?.requestStatus === "fulfilled") {
      props?.onHide();
      props?.setShowSucsessModal();
      setContact();
      setEmail();
    } else if (verify.meta?.requestStatus === "rejected") {
      setError("password", { type: "custom", message: verify.payload?.errors });
    }
  };

  const app_setup = useSelector((state) => state.master.app_setup);

  // useEffect(() => {
  //   dispatch(appSetup());
  // }, [dispatch]);

  return (
    <Modal
      className="Set_New_Password_Modal Reset_Password_Modal Login_Modal"
      size="md"
      {...props}
      centered
    >
      <Modal.Body>
        <div className="reset_pass_main_form">
          <div className="close_img_div">
            <div className="title_div">
              <p className="title">Set New Password</p>
              <p className="sub_text">
                Secure your account with a new password
              </p>
            </div>
            <img
              src="/assets/images/modal/close.png"
              className="close_img"
              onClick={() => {
                props?.onHide();
              }}
            />
          </div>

          <div className="reset_pass_div login_div">
            <div className="login_form_div">
              <Form>
                <Form.Group className="gray_input_group input_group">
                  <Form.Label className="label_text">
                    Enter new Password
                  </Form.Label>
                  <div className="password_holder">
                    <Form.Control
                      type={showPassword ? "text" : "password"}
                      name="password"
                      placeholder="Enter password"
                      {...register("password", {
                        required: "Password is required",
                        minLength: {
                          value: 8,
                          message:
                            "Password must be at least 8 characters long",
                        },
                        pattern: {
                          value: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/,
                          message:
                            "Password must contain at least one uppercase letter, one lowercase letter, and one number",
                        },
                      })}
                      onChange={(e) => setPassword(e.target.value)}
                    />
                    {errors?.password && (
                      <sup className="text-danger">
                        {errors?.password?.message}
                      </sup>
                    )}
                    <div className="eye-icc">
                      <FontAwesomeIcon
                        icon={iconOne}
                        className="icon"
                        onClick={() => togglePasswordVisibility("password")}
                      />
                    </div>
                  </div>
                </Form.Group>

                <Form.Group className="gray_input_group input_group">
                  <Form.Label className="label_text">
                    Enter your Confirm Password
                  </Form.Label>
                  <div className="password_holder">
                    <Form.Control
                      type={showPasswordOne ? "text" : "password"}
                      name="re_password"
                      placeholder="Enter Confirm Password"
                      // {...register("re_password", {
                      //   required: "Re-Enter Password  is required",
                      // })}
                      {...register("re_password", {
                        required: "Re-Enter Password is required",
                        validate: (value) =>
                          value === getValues("password") ||
                          "Passwords do not match",
                      })}
                      onChange={(e) => setPasswordAgain(e.target.value)}
                    />

                    <div className="eye-icc">
                      <FontAwesomeIcon
                        icon={iconTwo}
                        className="icon"
                        onClick={() =>
                          togglePasswordVisibility("reenterPassword")
                        }
                      />
                    </div>
                    {errors?.re_password && (
                      <sup className="text-danger">
                        {errors?.re_password?.message}
                      </sup>
                    )}
                  </div>
                </Form.Group>

                {password && (
                  <div className="password_check_list">
                    <PasswordChecklist
                      rules={[
                        "minLength",
                        "specialChar",
                        "number",
                        "capital",
                        "match",
                      ]}
                      minLength={8}
                      value={password}
                      valueAgain={passwordAgain}
                      onChange={(isValid) => {}}
                      style={{
                        fontSize: "10px",
                        padding: "4px",
                        margin: "0",
                      }}
                    />
                  </div>
                )}
              </Form>
            </div>

            <div className="btns_holder">
              <Black_Btn
                btnText={"Reset Password"}
                onClick={handleSubmit(onSubmit)}
              />
            </div>
          </div>
        </div>
      </Modal.Body>
    </Modal>
  );
};

export default Set_New_Password_Modal;
