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";
import Green_round_btn from "../../common_btn/green_round_btn/Green_round_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]);
  const [showForgotPassword, setShowForgotPassword] = useState(false);

  // animation code

  const [bodyAnimation, setBodyAnimation] = useState("slide-right");
  const [titleAnimation, setTitleAnimation] = useState("");
  const openSignup = () => {
    setTitleAnimation("title-slide-right");
    setBodyAnimation("slide-right");
    setShowSignUp(true);
  };

  const openLogin = () => {
    setTitleAnimation("title-slide-right");
    setBodyAnimation("slide-right");
    setShowSignUp(false);
  };

  return (
    <Modal
      className="Login_Modal Login_Modal-only "
      size="md"
      {...props}
      centered
    >
      {/* <div
        className={`absolute_div 
    ${showSignUp ? "signup_header" : ""}
  
  `}
      >
        <p
          key={`${showSignUp}-${titleAnimation}`}
          className={`modal_title ${titleAnimation}`}
        >
          {showSignUp ? "Sign Up" : "Login"}
        </p>

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

      {/* <Modal.Body> */}
      <Modal.Body
        key={`${showSignUp}-${bodyAnimation}`}
        className="login-modal-body"
      >
        <div className="top-content-wrapper">
          <div className="logo_holder">
            <img
              src={process.env.NEXT_PUBLIC_IMG_URL + app_setup?.logo}
              className="logo_img"
              alt="logo"
            />
          </div>

          <p>
            Join our family and make every moment with your furry
            friend special.
          </p>
        </div>

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

        {/* LOGIN / SIGN UP TABS */}
        <div className="auth-tabs">
          <button
            type="button"
            className={`auth-tab ${!showSignUp ? "active" : ""}`}
            onClick={openLogin}
          >
            Login
          </button>

          <button
            type="button"
            className={`auth-tab ${showSignUp ? "active" : ""}`}
            onClick={openSignup}
          >
            Create Account
          </button>
        </div>

        <div className="auth-tab-line">
          <div
            className={`auth-tab-indicator ${
              showSignUp ? "signup-active" : ""
            }`}
          />
        </div>

        {/* LOGIN */}
        {!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"
                    placeholder="Enter Email / Mobile Number"
                    {...register("email_or_contact", {
                      required: "Credentials required",
                    })}
                  />

                  {errors?.email_or_contact && (
                    <p className="text-danger">
                      {errors.email_or_contact.message}
                    </p>
                  )}
                </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*"
                      {...register("password", {
                        required: "Password is required",
                      })}
                    />

                    <div className="eye-icc">
                      <FontAwesomeIcon
                        icon={iconOne}
                        className="icon"
                        onClick={() => togglePasswordVisibility("password")}
                      />
                    </div>
                  </div>

                  {errors?.password && (
                    <p className="text-danger">{errors.password.message}</p>
                  )}

                  <p
                    className="link_text"
                    onClick={() => {
                      props?.onHide();
                      props?.setShowResetModal();
                    }}
                  >
                    Forgot Password?
                  </p>
                </Form.Group>
              </Form>
            </div>

            <div className="btn_holder">
              <Black_Btn btnText="Login" onClick={handleSubmit(onSubmit)} />
            </div>
          </div>
        )}

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

export default Login_Modal;
