import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
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();

  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);
  };

  // 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();

  const doLogin = async () => {
    try {
      if (email !== "" && password !== "") {
        var postData = {
          username: email,
          password: password,
          sessionid: "STARTING",
        };
        const loginResult = await userApi.logInUser(postData); // just for a test
        //debugger;
        // if (email === "support@mermsemr.com") {
        if (
          loginResult.data.status > 0 &&
          loginResult.data.internal_return == 100 &&
          loginResult.data.session != ""
        ) {
          // just for a start
          localStorage.setItem("member_id", `${loginResult.data.member_id}`);
          localStorage.setItem("uid", `${loginResult.data.uid}`);
          localStorage.setItem("session_token", `${loginResult.data.session}`);
          localStorage.setItem("session", `${loginResult.data.session}`);
          setLoginLoading(true);
          // userApi.getUserReminders(); //testing
          dispatch(updateUserDetails(loginResult.data));
          setTimeout(() => {
            navigate("/", { replace: true });
            setLoginLoading(false);
          }, 2000);
        } else {
          // toast.error("Invalid Credential");
          setLoginError(true);
        }
      } else {
        setMsgError("Please fill in the fields");
      }
    } catch (error) {
      setMsgError("An error occurred");
    } finally {
      setTimeout(() => {
        setLoginError(false);
        setMsgError(null);
      }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT));
    }
  };

  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>
              <div className="input-area">
                <div className="input-item mb-5">
                  <InputCom
                    fieldClass="px-6"
                    value={email}
                    inputHandler={handleEmail}
                    placeholder="support@mermsemr.com"
                    label="Email"
                    name="email"
                    type="email"
                    iconName="message"
                  />
                </div>

                <div className="input-item mb-5">
                  <InputCom
                    fieldClass="px-6"
                    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
                      onClick={doLogin}
                      type="button"
                      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>
                      ) : (
                        <span>Continue</span>
                      )}
                    </button>
                  </div>
                  <BrandBtn link="#"  imgSrc={googleLogo} brand="Google" />
                  <BrandBtn link="#"   imgSrc={facebookLogo} brand="Facebook" />
                  <BrandBtn link="#"    imgSrc={appleLogo} brand="Apple" />
                </div>
                {/* <div className="signup-area flex justify-center">
                <p className="sm:text-lg text-sm text-thin-light-gray font-normal">
                  Don't have an account ?
                  <a href="/signup" className="ml-2   text-dark-gray dark:text-white">
                    Sign up free
                  </a>
                </p>
              </div> */}
                <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>
        </div>
      </AuthLayout>
    </>
  );
}

const BrandBtn = ({ link, imgSrc, brand }) => {

  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="flex justify-center bottomMargin">
      <a
          // onClick={doGoogle}
          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>
      </a>
    </div>
  );
};
