import React, { useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import { toast } from "react-toastify";
import googleLogo from "../../../assets/images/google-logo.svg";
import appleLogo from "../../../assets/images/apple-black.svg";
import facebookLogo from "../../../assets/images/facebook-4.svg";
import WrenchBoard from "../../../assets/images/wrenchboard.png"
import usersService from "../../../services/UsersService";
import InputCom from "../../Helpers/Inputs/InputCom";
import AuthLayout from "../AuthLayout";

export default function Login() {
  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 () => {
    if (email == '' && password == '') {
      setMsgError('Please fill in fields')
    }
    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("email", `${loginResult.data.email}`);
          localStorage.setItem("member_id", `${loginResult.data.member_id}`);
          localStorage.setItem("uid", `${loginResult.data.uid}`);
          localStorage.setItem("session_token", `${loginResult.data.session}`);
          localStorage.setItem("added", `${loginResult.data.added}`);
          localStorage.setItem("city", `${loginResult.data.city}`);
          localStorage.setItem("country", `${loginResult.data.country}`);
          localStorage.setItem("firstname", `${loginResult.data.firstname}`);
          localStorage.setItem("last_login", `${loginResult.data.last_login}`);
          localStorage.setItem("lastname", `${loginResult.data.lastname}`);
          localStorage.setItem("state", `${loginResult.data.state}`);
          localStorage.setItem("zip_code", `${loginResult.data.zip_code}`);
          localStorage.setItem("session", `${loginResult.data.session}`);
          setLoginLoading(true);
          // userApi.getUserReminders(); //testing
          setTimeout(() => {
            navigate("/", { replace: true });
            setLoginLoading(false);
          }, 2000);
        } else {
          // toast.error("Invalid Credential");
          setLoginError(true)
        }
      }
    } 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
                    value={email}
                    inputHandler={handleEmail}
                    placeholder="support@mermsemr.com"
                    label="Email"
                    name="email"
                    type="email"
                    iconName="message"
                  />
                </div>

                <div className="input-item mb-5">
                  <InputCom
                    value={password}
                    inputHandler={handlePassword}
                    placeholder="● ● ● ● ● ●"
                    label="Password"
                    name="password"
                    type="password"
                    iconName="password"
                    forgotPassword
                  />
                </div>
                {/* <div className="forgot-password-area flex justify-between items-center mb-7">
                <div className="remember-checkbox flex items-center space-x-2.5">
                  <button
                    onClick={rememberMe}
                    type="button"
                    className="w-5 h-5 text-dark-gray dark:text-white flex justify-center items-center border border-light-gray"
                  >
                    {checked && (
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="h-5 w-5"
                        viewBox="0 0 20 20"
                        fill="currentColor"
                      >
                        <path
                          fillRule="evenodd"
                          d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                          clipRule="evenodd"
                        />
                      </svg>
                    )}
                  </button>
                  <span
                    onClick={rememberMe}
                    className="text-base text-dark-gray dark:text-white"
                  >
                    Remember Me
                  </span>
                </div>
                <a href="/forgot-password" className="text-base text-purple">
                  Forgot Password
                </a>
              </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
}) => {
  return (
    <div className="flex justify-center bottomMargin">
      <a
        href={link}
        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>
  )
}