import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import linkedInLogo from "../../../assets/images/Linkedin.png";
import appleLogo from "../../../assets/images/apple-black.svg";
import facebookLogo from "../../../assets/images/facebook-4.svg";
import googleLogo from "../../../assets/images/google-logo.svg";
import WrenchBoard from "../../../assets/images/wrenchboard.png";
import usersService from "../../../services/UsersService";
import InputCom from "../../Helpers/Inputs/InputCom";
import AuthLayout from "../AuthLayout";
// import { GoogleOAuthProvider } from '@react-oauth/google';
import { googleLogout, useGoogleLogin } from "@react-oauth/google";

import { useDispatch } from "react-redux";
import { updateUserDetails } from "../../../store/UserDetails";

export default function Login() {
  const dispatch = useDispatch();

  let [loginType, setLoginType] = useState({ full: true, family: false });

  const [checked, setValue] = useState(false);
  const [loginLoading, setLoginLoading] = useState(false);

  //login error state
  const [loginError, setLoginError] = useState(false);
  // for the catch error
  const [msgError, setMsgError] = useState("");

  const rememberMe = () => {
    setValue(!checked);
  };

  //FUNCTION TO DETERMINE/CHANGE LOGIN COMPONENT
  const handleLoginType = ({ target: { name } }) => {
    if (name == "full") {
      setLoginType({ [name]: true, family: false });
    } else if ((name = "family")) {
      setLoginType({ [name]: false, family: true });
    }
  };

  // email
  const [email, setMail] = useState("");
  const handleEmail = (e) => {
    setMail(e.target.value);
  };
  // password
  const [password, setPassword] = useState("");
  const handlePassword = (e) => {
    setPassword(e.target.value);
  };
  const navigate = useNavigate();
  const userApi = new usersService();

  // FUNCTION TO HANDLE USER LOGIN
  const doLogin = ({ target: { name } }) => {
    setMsgError("");
    setLoginError(false);
    setLoginLoading(true);
    let postData; // Post Data for API
    if (!email || !password) {
      setLoginLoading(false);
      setMsgError("Please fill all the fields");
      setTimeout(() => {
        setMsgError("");
      }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT));
      return;
    }

    if (name == "loginfull") {
      // Post Data Info for normal Login
      postData = {
        username: email,
        password: password,
        sessionid: "STARTING",
        login_mode: 1100,
        action: 11025,
      };
    } else if (name == "loginfamily") {
      // Post Data Info for family Login
      postData = {
        username: email,
        pin: password,
        sessionid: "20067A92714",
        login_mode: 1105,
        action: 11025,
      };
    } else {
      setLoginLoading(false);
      setMsgError("Invalid Login Type. Consider refreshing the page");
      setTimeout(() => {
        setMsgError("");
      }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT));
      return;
    }
    userApi
      .logInUser(postData)
      .then((res) => {
        if (res.status != 200 || res.data.internal_return < 0) {
          // setMsgError("Wrong, email/password");
          setLoginError(true);
          setLoginLoading(false);
          return;
        }
        localStorage.setItem("member_id", `${res.data.member_id}`);
        localStorage.setItem("uid", `${res.data.uid}`);
        localStorage.setItem("session_token", `${res.data.session}`);
        // localStorage.setItem("session", `${res.data.session}`);
        dispatch(updateUserDetails(res.data));
        setTimeout(() => {
          navigate("/", { replace: true });
          setLoginLoading(false);
        }, 2000);
      })
      .catch((error) => {
        setMsgError("Unable to login, try again");
        setLoginLoading(false);
      })
      .finally(() => {
        setTimeout(() => {
          setLoginError(false);
          setMsgError("");
          setLoginLoading(false);
        }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT));
      });
  };

  const googleLogin = useGoogleLogin({
    flow: 'auth-code',
    ux_mode:'redirect',
    redirect_uri: process.env.REACT_APP_GOOGLE_REDIRECT_URL,
    onSuccess: async (codeResponse) => {
      console.log(codeResponse);
    },
    onError: (errorResponse) => console.log(errorResponse),
  });

  useEffect(() => {
    setMail("");
    setPassword("");
  }, [loginType.full, loginType.family]);

  return (
    <>
      <AuthLayout slogan="Welcome to WrenchBoard">
        <div className="w-full">
          <div className="mb-12">
            <Link to="#">
              <img
                src={WrenchBoard}
                alt="wrenchboard"
                className="h-10 mx-auto"
              />
            </Link>
          </div>
          <div className="content-wrapper login shadow-md w-full lg:max-w-[500px] mx-auto flex justify-center items-center xl:bg-white dark:bg-dark-white 2xl:w-[828px]  rounded-[0.475rem] sm:p-7 p-5">
            <div className="w-full">
              <div className="title-area flex flex-col justify-center items-center relative text-center mb-7">
                {/* <h1 className="text-[#181c32] font-semibold dark:text-white mb-3 leading-[27.3px] text-[22.75px]">
                  Sign In to WrenchBoard
                </h1> */}
                <span className="text-gray-400 font-medium text-[16.25px] leading-[24.375px]">
                  New Here?{" "}
                  <Link
                    to="/signup"
                    className="font-semibold text-[#4687ba] hover:text-[#009ef7] transition"
                  >
                    Create an Account
                  </Link>
                </span>
              </div>

              {/* switch login component */}
              <div className="flex justify-start items-end">
                <button
                  name="full"
                  className={`px-2 py-1 w-[100px] text-left h-[40px] text-lg font-bold text-[#4687ba] hover:text-[#009ef7] tracking-wide transition outline-none border-2 border-b-0 border-r-0 border-[#4687ba] ${
                    loginType.full && "border-r-2 h-[45px]"
                  }`}
                  onClick={handleLoginType}
                >
                  Sign in
                </button>
                <button
                  name="family"
                  className={`px-2 py-1 w-[100px] text-left h-[40px] text-lg font-bold text-[#4687ba] hover:text-[#009ef7] tracking-wide transition outline-none border-2 border-b-0 border-l-0 border-[#4687ba] ${
                    loginType.family && "border-l-2 h-[45px]"
                  }`}
                  onClick={handleLoginType}
                >
                  Family
                </button>
              </div>

              {/* END  of switch login component */}

              {/* for login component */}
              {
                loginType.full ? (
                  //user login component
                  <div className="p-2 input-area border-2 border-[#4687ba]">
                    <div className="input-item mb-5">
                      <InputCom
                        labelClass="tracking-wider"
                        fieldClass="sm:px-6 px-2"
                        value={email}
                        inputHandler={handleEmail}
                        placeholder="support@mermsemr.com"
                        label="Email"
                        name="email"
                        type="email"
                        iconName="message"
                      />
                    </div>

                    <div className="input-item mb-5">
                      <InputCom
                        labelClass="tracking-wider"
                        fieldClass="sm:px-6 px-2"
                        value={password}
                        inputHandler={handlePassword}
                        placeholder="● ● ● ● ● ●"
                        label="Password"
                        name="password"
                        type="password"
                        iconName="password"
                        forgotPassword
                      />
                    </div>
                    {loginError && (
                      <div className="relative p-4 text-[#912741] bg-[#fcd9e2] border-[#fbc6d3] mb-4 rounded-[0.475rem] text-md font-thin leading-[19.5px] text-[13px]">
                        Invalid username or password- Please{" "}
                        <Link to="/#" className="text-[#009ef7]">
                          reset your password
                        </Link>{" "}
                        or{" "}
                        <Link to="/signup" className="text-[#009ef7]">
                          create a new account
                        </Link>
                      </div>
                    )}
                    {msgError && (
                      <div className="relative p-4 text-[#912741] bg-[#fcd9e2] border-[#fbc6d3] mb-4 rounded-[0.475rem] text-md font-light leading-[19.5px] text-[13px]">
                        {msgError}
                      </div>
                    )}
                    <div className="signin-area mb-3.5">
                      <div className="flex justify-center">
                        <button
                          name="loginfull"
                          onClick={doLogin}
                          type="button"
                          disabled={loginLoading}
                          className={`btn-login  rounded-[0.475rem] mb-6 text-xl text-white flex justify-center bg-[#4687ba] hover:bg-[#009ef7] transition-all duration-300 items-center text-[15px]`}
                        >
                          {loginLoading ? (
                            <div className="signup btn-loader"></div>
                          ) : (
                            <>Continue</>
                          )}
                        </button>
                      </div>
                      <div className="sm:flex sm:justify-between sm:items-center sm:space-x-2">
                        <BrandBtn
                          link="#"
                          imgSrc={googleLogo}
                          brand="Google"
                          onClick={googleLogin}
                        />
                        <BrandBtn link="#" imgSrc={appleLogo} brand="Apple" />
                      </div>
                      <div className="sm:flex sm:justify-between sm:items-center sm:space-x-2">
                        <BrandBtn
                          link="#"
                          imgSrc={facebookLogo}
                          brand="Facebook"
                        />
                        <BrandBtn
                          link="#"
                          imgSrc={linkedInLogo}
                          brand="LinkedIn"
                        />
                      </div>
                    </div>
                  </div>
                ) : (
                  // END of user login compoenent
                  // family login compoenent
                  <div className="p-2 input-area border-2 border-[#4687ba]">
                    <div className="input-item mb-5">
                      <InputCom
                        labelClass="tracking-wider"
                        fieldClass="px-6"
                        value={email}
                        inputHandler={handleEmail}
                        placeholder="support@mermsemr.com"
                        label="Username"
                        name="email"
                        type="email"
                        iconName="message"
                      />
                    </div>

                    <div className="input-item mb-5">
                      <InputCom
                        labelClass="tracking-wider"
                        fieldClass="px-6"
                        value={password}
                        inputHandler={handlePassword}
                        placeholder="● ● ● ● ● ●"
                        label="Pin"
                        name="password"
                        type="password"
                        iconName="password"
                        // forgotPassword
                      />
                    </div>
                    {loginError && (
                      <div className="relative p-4 text-[#912741] bg-[#fcd9e2] border-[#fbc6d3] mb-4 rounded-[0.475rem] text-md font-thin leading-[19.5px] text-[13px]">
                        Invalid username or password{" "}
                        {/* <Link to="/#" className="text-[#009ef7]">
                        reset your password
                      </Link>{" "}
                      or{" "}
                      <Link to="/signup" className="text-[#009ef7]">
                        create a new account
                      </Link> */}
                      </div>
                    )}
                    {msgError && (
                      <div className="relative p-4 text-[#912741] bg-[#fcd9e2] border-[#fbc6d3] mb-4 rounded-[0.475rem] text-md font-light leading-[19.5px] text-[13px]">
                        {msgError}
                      </div>
                    )}
                    <div className="signin-area mb-1.5">
                      <div className="flex justify-center">
                        <button
                          name="loginfamily"
                          onClick={doLogin}
                          disabled={loginLoading}
                          type="button"
                          className={`btn-login  rounded-[0.475rem] text-xl text-white flex justify-center bg-[#4687ba] hover:bg-[#009ef7] transition-all duration-300 items-center text-[15px]`}
                        >
                          {loginLoading ? (
                            <div className="signup btn-loader"></div>
                          ) : (
                            <>Continue</>
                          )}
                        </button>
                      </div>
                    </div>
                  </div>
                )
                // END of family login compoenent
              }
              {/* END of login component */}

              <div className="pt-5 text-[#181c32] text-center font-semibold text-[13.975px] leading-[20.9625px]">
                This site is protected by hCaptcha and the our Privacy Policy
                and Terms of Service apply.
              </div>
            </div>
          </div>
        </div>
      </AuthLayout>
    </>
  );
}

const BrandBtn = ({ link, imgSrc, brand, onClick }) => {
  // const doGoogle = async () => {
  //   alert("start google");
  // };

  //  onSuccess: (codeResponse) => setUser(codeResponse),

  // const doGoogle = useGoogleLogin({
  //   onSuccess: (codeResponse) =>  console.log('Login onSuccess:', codeResponse),
  //   onError: (error) => console.log('Login Failed:', error)
  // });

  // const doApple = async () => {
  //   alert("start apple");
  // };

  // const doFacebook = async () => {
  //   alert("start facebook");
  // };

  return (
    <div className="w-full sm:w-1/2 flex justify-center bottomMargin">
      <button
        onClick={onClick}
        // href="#dd"
        className="w-full border border-light-purple dark:border-[#5356fb29]  rounded-[0.475rem] h-[48px] flex justify-center bg-[#FAFAFA] hover:bg-[#eff2f5] hover:text-[#7e8299] transition duration-300 dark:bg-[#11131F]  items-center font-medium cursor-pointer"
      >
        <img className="mr-3 h-6" src={imgSrc} alt="logo-icon(s)" />
        <span className="text-lg text-thin-light-gray font-normal text-[15px]">
          Continue with {brand}
        </span>
      </button>
    </div>
  );
};
