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 Business_Login from "./Business_Login";
import Business_Signup from "./Business_Signup";
import { RoleId } from "../../../../utils/common";
const Login_Modal = ({ email, contact, setContact, setEmail, ...props }) => {
  const [showSignUp, setShowSignUp] = useState(false);
  const [activeTab, setActiveTab] = useState("customer");
  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 [authMode, setAuthMode] = useState("login");

  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) => {
    data.role_id = RoleId.Customer;
    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);

 

  return (
    <Modal className="Login_Modal" size="lg" {...props} centered>
      <div className="auth_header">
        <div className="wrapper-div">
          <img
            src={process.env.NEXT_PUBLIC_IMG_URL + app_setup?.logo}
            className="logo_img"
            alt="logo"
          />
          <div>
            <h3 className="auth_title">
              {activeTab === "customer"
                ? authMode === "login"
                  ? "Customer Login"
                  : "Customer Registration"
                : authMode === "login"
                  ? "Business Login"
                  : "Business Registration"}
            </h3>

            <p className="auth_subtitle">
              {activeTab === "customer"
                ? showSignUp
                  ? "Create your customer account"
                  : "Login to your customer account"
                : showSignUp
                  ? "Register your business with us"
                  : "Login to your business account"}
            </p>
          </div>
        </div>
        <div className="close_img_div">
          <img
            src="/assets/images/modal/close.png"
            className="close_img"
            onClick={() => {
              props?.onHide();
            }}
          />
        </div>
      </div>
      {/* <Modal.Body>
        <div className="login-tabs">
          <button
            className={activeTab === "customer" ? "active" : ""}
            onClick={() => {
              setActiveTab("customer");
              setShowSignUp(false);
            }}
          >
            {showSignUp && activeTab === "customer"
              ? "Customer Sign Up"
              : "Customer Login"}
          </button>

          <button
            className={activeTab === "b2b" ? "active" : ""}
            onClick={() => {
              setActiveTab("b2b");
              setShowSignUp(false);
            }}
          >
            {showSignUp && activeTab === "b2b" ? "B2B Sign Up" : "B2B Login"}
          </button>
        </div>
        
        {!showSignUp && (
          <>
            {activeTab === "customer" && (
              <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)}
                 
                  />
                </div>

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

        {activeTab === "customer" && showSignUp && (
          <SignUp_Modal
            setShowSignUp={setShowSignUp}
            showSignUp={showSignUp}
            setShowAccountCreted={props?.setShowAccountCreted}
            onHide={props?.onHide}
          />
        )}

        {activeTab === "b2b" && showSignUp && (
          <Business_Signup setShowSignUp={setShowSignUp} />
        )}
      </Modal.Body> */}

      <Modal.Body>
        <div className="login-tabs">
          <button
            className={activeTab === "customer" ? "active" : ""}
            onClick={() => setActiveTab("customer")}
          >
            {authMode === "login" ? "Customer Login" : "Customer Sign Up"}
          </button>

          <button
            className={activeTab === "b2b" ? "active" : ""}
            onClick={() => setActiveTab("b2b")}
          >
            {authMode === "login" ? "B2B Login" : "B2B Sign Up"}
          </button>
        </div>

        {/* CUSTOMER */}
        {activeTab === "customer" &&
          (authMode === "login" ? (
            <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 && (
                      <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"
                        {...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>
                  </Form.Group>
                </Form>
              </div>

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

              <p className="dark_text">
                Don't have an account?{" "}
                <span
                  className="link_text"
                  onClick={() => setAuthMode("signup")}
                >
                  Create Account
                </span>
              </p>
            </div>
          ) : (
            <SignUp_Modal
              setAuthMode={setAuthMode}
              setShowAccountCreted={props?.setShowAccountCreted}
              onHide={props?.onHide}
            />
          ))}

        {/* B2B */}
        {activeTab === "b2b" &&
          (authMode === "login" ? (
            <Business_Login
              setAuthMode={setAuthMode}
              onHide={props?.onHide}
              setShowLogin={props.setShowLogin}
            />
          ) : (
            <Business_Signup
              setAuthMode={setAuthMode}
              setShowAccountCreted={props?.setShowAccountCreted}
              onHide={props?.onHide}
            />
          ))}
      </Modal.Body>
    </Modal>
  );
};

export default Login_Modal;
