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 "./Login_Modal.css";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
import PasswordChecklist from "react-password-checklist";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Reset_Password_Modal from "../reset_password_modal/Reset_Password_Modal";
import { useDispatch, useSelector } from "react-redux";
import { UserLogin, userSignUp } from "../../../../features/auth/authSlice";
import SignUp_Modal from "./Signup_Modal";
import { myAccount } from "../../../../features/my_account/Slice";
import { getAllCart } from "../../../../features/cart/cartSlice";
import { getAllWishlist } from "../../../../features/wishlist/wishlistSlice";
import Green_btn from "../../common_btn/green_btn/Green_btn";
import { appSetup } from "../../../../features/master/masterSlice";
import Black_Btn from "../../common_btn/black_btn/Black_Btn";

const Login_Modal = ({ email, contact, setContact, setEmail, ...props }) => {
  const [showSignUp, setShowSignUp] = useState(false);

  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 {
    control,
    register,
    handleSubmit,
    getValues,
    setValue,
    setError,
    clearErrors,
    formState: { errors },
    reset,
    trigger,
  } = useForm();

  const dispatch = useDispatch();
  const isSignin = useSelector((state) => state.auth.is_signin);
  const onSubmit = async (data) => {
    const res = await dispatch(UserLogin(data));

    if (res.meta?.requestStatus === "fulfilled") {
      dispatch(getAllCart(isSignin));
      dispatch(getAllWishlist());
      dispatch(myAccount());
      props?.onHide();
      props.setShowLogin();
      // setTimeout(() => {
      //   // navigate("/home");
      // }, 3000);
    } else if (res.meta?.requestStatus === "rejected") {
      if (res.payload?.errors?.email_or_contact) {
        setError("email_or_contact", {
          type: "manual",
          message: res.payload?.errors?.email_or_contact,
        });
      }
      if (res.payload?.errors?.password) {
        setError("password", {
          type: "manual",
          message: res.payload?.errors?.password,
        });
      }
    }
  };
  const user = useSelector((state) => state.myaccount.addMyaccount);

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

  const app_setup = useSelector((state) => state.master.app_setup);
  // useEffect(() => {
  //   dispatch(appSetup());
  // }, [dispatch]);

  return (
    <Modal className="Login_Modal" size="md" {...props} centered>
      <div className="absolute_div">
        <p className="modal_title">{showSignUp ? "SIGN UP" : "LOGIN"}</p>

        <div className="logo_holder">
          <img
            // src="/assets/images/logo/new_ekansi_logo.png"
            src={process.env.NEXT_PUBLIC_IMG_URL + app_setup?.logo}
            className="logo_img"
          />
        </div>
      </div>

      <Modal.Body>
        <div className="close_img_div">
          <img
            src="/assets/images/modal/close.png"
            className="close_img"
            onClick={() => {
              props?.onHide();
            }}
          />
        </div>

        {!showSignUp && (
          <div className="login_div">
            <div className="login_form_div">
              <Form>
                <Form.Group className="gray_input_group input_group">
                  <Form.Label>Email / Mobile Number</Form.Label>
                  <Form.Control
                    type="text"
                    name="email_or_contact"
                    placeholder="Enter Email / Mobile Number"
                    {...register("email_or_contact", {
                      required: "Credentials required",
                    })}
                  />
                  {errors?.email_or_contact && (
                    <sup className="text-danger">
                      {errors?.email_or_contact?.message}
                    </sup>
                  )}
                </Form.Group>

                <Form.Group className="gray_input_group input_group">
                  <Form.Label>Password</Form.Label>
                  <div className="password_holder">
                    <Form.Control
                      type={showPassword ? "text" : "password"}
                      placeholder="Enter Password*"
                      name="password"
                      {...register("password", {
                        required: "Password is required",
                      })}
                    />
                    <div className="eye-icc">
                      <FontAwesomeIcon
                        icon={iconOne}
                        className="icon"
                        onClick={() => togglePasswordVisibility("password")}
                      />
                    </div>
                  </div>
                  {errors?.password && (
                    <sup className="text-danger">
                      {errors?.password?.message}
                    </sup>
                  )}
                  <p
                    className="link_text"
                    onClick={() => {
                      props?.onHide();
                      props?.setShowResetModal();
                    }}
                  >
                    Forgot Password?
                  </p>

                  {errors.name && (
                    <div className="invalid-feedback">
                      {errors.name.message}
                    </div>
                  )}
                </Form.Group>
              </Form>
            </div>

            <div className="btn_holder">
              <Black_Btn
                btnText="Login"
                onClick={handleSubmit(onSubmit)}
                // onClick={() => {
                //   props?.onHide();
                // }}
              />
            </div>

            <p className="dark_text">
              Don't have an account?{" "}
              <span
                className="link_text"
                onClick={() => {
                  setShowSignUp(true);
                }}
              >
                Create Account
              </span>
              .
            </p>

        
          </div>
        )}

        {showSignUp && (
          <SignUp_Modal
            setShowSignUp={setShowSignUp}
            showSignUp={showSignUp}
            setShowAccountCreted={props?.setShowAccountCreted}
            onHide={props?.onHide}
          />
        )}
      </Modal.Body>
    </Modal>
  );
};

export default Login_Modal;
