import React, { useState } from "react";
import "./Change_Password.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faEye,
  faEyeSlash,
} from "@fortawesome/free-solid-svg-icons";
import { Form } from "react-bootstrap";
import "react-phone-input-2/lib/style.css";
import { useForm, Controller } from "react-hook-form";
import Green_btn from "../../../common-components/common_btn/green_btn/Green_btn";
import PasswordChecklist from "react-password-checklist";
import { useDispatch } from "react-redux";
import { ChangePassword } from "../../../../features/user/userSlice";
import Success_Modal from "../../../common-components/common_modal/success_modal/Success_Modal";


const Change_Password = () => {
  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 breadcrumbs = [
    { label: "Home", link: "/", active: false },
    {
      label: "My Account",
      link: "",
      active: true,
    },
  ];

  const {
    control,
    register,
    handleSubmit,
    getValues,
    setValue,
    setError,
    clearErrors,
    formState: { errors },
    reset,
    trigger, watch
  } = useForm();

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

  const [showAccountCreted, setShowAccountCreted] = useState(false);
  const dispatch = useDispatch();
  const onSubmit = async (data) => {

    const res = await dispatch(ChangePassword(data));


    if (res.meta?.requestStatus === "fulfilled") {

      setShowAccountCreted(true);
      reset();
      setTimeout(() => {
        setShowAccountCreted(false);
      }, 5000);
    } else if (res.meta?.requestStatus === "rejected") {
      if (res.payload?.errors) {
        setError("old_password", {
          type: "manual",
          message: res.payload?.errors,
        });
      }
    }
  };
  const oldPasswordValue = watch("old_password");
  return (
    <>
      <p className="change_pwd_section_title">Change Password</p>
      <section className="Change_Password Personal_Info">
        <div className="personal_info_form">
          <Form>
            <Form.Group className="input_group">
              <Form.Label className="label_text">Old Password</Form.Label>
              <div className="password_holder">
                <Form.Control
                  type={showPassword ? "text" : "password"}
                  name="password"
                  {...register("old_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",
                    },
                  })}

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

            <Form.Group className="input_group">
              <Form.Label className="label_text"> Password</Form.Label>
              <div className="password_holder">
                <Form.Control
                  type={showPassword ? "text" : "password"}
                  name="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",
                    },
                    validate: (value) =>
                      value !== oldPasswordValue ||
                      "New password must be different from old password",
                  })}
                  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="input_group">
              <Form.Label className="label_text">Confirm Password</Form.Label>
              <div className="password_holder">
                <Form.Control
                  type={showPasswordOne ? "text" : "password"}
                  name="re_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>
            )}

            <div className="btns_holder">
              <div className="save_btn">
                <Green_btn btnText="Save" onClick={handleSubmit(onSubmit)} />
              </div>
              {/* <div className="cancel_btn">
                <Green_round_btn btnText="Cancel" />
              </div> */}
            </div>
          </Form>
        </div>
      </section>

      <Success_Modal
        show={showAccountCreted}
        onHide={() => {
          setShowAccountCreted(false);
        }}
        successText="Password Update Successfully!"
      />
    </>
  );
};

export default Change_Password;
