import React, { useState, useContext, useEffect } from "react";

import { Form, Input, message, Result } from "antd";

import { withRouter, Link } from "react-router-dom";

import backgroundImage from './../../../assets/images/vector.png'

import OTPInput from "otp-input-react";

import { motion } from "framer-motion";

import { Button } from "../../elements";

import "./login.scss";

// import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

// import { faCheck } from "@fortawesome/free-solid-svg-icons";

import FirebaseUtils from "../../../lib/utils/firebase.utils";

import ApiUtils from "../../utils/api/api.utils";

import { GlobalContext } from "./../../Store";

const layout = {
  labelCol: { span: 24 },

  wrapperCol: { span: 24 },
};

const tailLayout = {
  wrapperCol: { span: 8 },
};

/**
 * 
 * @param {*} param0 
 * @returns 
 */
function LoginPhone({ history, appSettings }) {

  const { brandLogo, heroImage, footerLogo, headers } = appSettings;

  const { dispatch, state } = useContext(GlobalContext);
  // variabel used for btnloading

  const [loading, setLoading] = useState(false);

  const [ldaploading, setLdapLoading] = useState(false);

  // variable used to show otp generating

  const [otpVisible, setOtpVisible] = useState(false);
  // variabale used to show otp entering screen

  const [otpVerification, setotpVerification] = useState(false);

  const [otpValue, setOtpValue] = useState("");
  // setting user credentials
  const [user, setUser] = useState([]);

  const onFinish = (values) => {
    setLoading(true);

    if (process.env.REACT_APP_PRIMARY_BACKEND === "SQL") {
      let formBody = {
        username: values.email,

        password: values.password,
      };

      return ApiUtils.post({ url: "auth/login", formBody, headers })

        .then((result) => {
          setLoading(false);

          const { user, access_token } = result;

          localStorage.access_token = access_token;

          if (result.success) {

            //two_factor_authentication variable is present then proceed Two factor authentication
            if (result.data && result.data.two_factor_authentication) {
              let data;

              // set variable used for otp send screen
              setOtpVisible(true);

              // set user credentials
              data = {
                username: result.data.email,
                password: values.password,
                mode: result.data.mode ? result.data.mode : null,
                mobile: result.data.mobile ? result.data.mobile : null
              };

              // set user values
              setUser(data);

            } else {
              let d = user;

              let userInfo = {
                id: user.id,
                locations: [],
                ...d,
                ...{
                  loggedCheckDone: true,
                },
              };

              dispatch({ type: "user", payload: userInfo });

              localStorage.setItem("userInfo", JSON.stringify(userInfo));

              history.push("/");
            }
          } else {
            message.error(result.message);
          }
        })
        .catch((error) => {
          console.log(error);

          message.error("This operation has failed.");

          setLoading(false);
        });
    } else {
      FirebaseUtils.loginWithEmail(values)

        .then((result) => {
          setLoading(false);

          if (result.id) {
            if (result.active) {
              let d = result;

              let userInfo = {
                id: result.id,
                locations: [],
                ...d,
                ...{
                  loggedCheckDone: true,
                },
              };

              if (result.role && result.role.name === "admin") {
                userInfo.isAdmin = true;
              }

              dispatch({ type: "user", payload: userInfo });

              localStorage.setItem("userInfo", JSON.stringify(userInfo));

              history.push("/");
            } else {
              message.error(
                "Your account is inactive, Please contact support."
              );
            }
          } else {
            message.error("No accounts found.");
          }
        })
        .catch((result) => {
          console.log(result);

          setLoading(false);

          message.error("Login Failed");
        });
    }
  };

  /**
   *
   * Function to implement 2 factor authentication on login
   *
   */
  const sendAuthenticationOtp = () => {
    setLoading(true);
    // set formbody
    let formBody;
    formBody = {
      email: user.username,
      mode: user.mode
    };

    // api used to send otp corresponding mail address
    return ApiUtils.post({
      url: "auth/send-authentication-otp",
      formBody,
      headers,
    }).then((result) => {
      // if the api is sucess then go for otpverification step
      if (result.success) {
        // if the api is sucess then go for otpverification step
        setotpVerification(true);
        // set  button loading false
        setLoading(false);
      } else {
        setLoading(false);
        message.error(result.message);
      }
    });
  };

  /**
   * Function to implement 2 factor authentication verification
   * @returns
   */

  const verifyOtp = () => {
    setLoading(true);
    let formBody;
    // set formBody
    formBody = {
      username: user.username,
      password: user.password,
      mode: user.mode,
      mobile: user.mobile,
      otp: otpValue,
    };
    // verifying is otp is correct or not
    return ApiUtils.post({
      url: "auth/verify-authentication-otp",
      formBody,
      headers,
    }).then((result) => {
      if (result.success) {
        setLoading(false);
        let d = result.user;

        // Setting access_token

        localStorage.access_token = result.access_token;
        // set user info
        let userInfo = {
          id: result.user.id,
          locations: [],
          ...d,
          ...{
            loggedCheckDone: true,
          },
        };

        dispatch({ type: "user", payload: userInfo });
        // set user info into local storage
        localStorage.setItem("userInfo", JSON.stringify(userInfo));
        history.push("/");
      } else {
        setLoading(false);
        message.error(result.message);
      }
    });
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);

    setLoading(false);

    setOtpVisible(false);
  };

  /**
   * otp onange
   * @param {*} value
   */
  const handleOtpChange = (value) => {
    setOtpValue(value);
  };

  /**
   * Otp resend Logic
   */
  const handleResendOTP = () => {
    // Resend OTP logic
    setOtpVisible(true);
    setotpVerification(false);

    // when resend the otp . otpvalue reset
    setOtpValue("");
  };

  /**
   * Cancel  otp send process
   */
  const handlecancel = () => {
    setOtpVisible(false);
    setotpVerification(false);
  }

  useEffect(() => {
    // Dynamically set the CSS variables based on the current theme
    // document.documentElement.style.setProperty('--custom-text-color', state.theme.colors.colorText);
    // document.documentElement.style.setProperty('--custom-bg-color', state.theme.colors.primaryButtonBg);
    // document.documentElement.style.setProperty('--custom-btn-text-color', state.theme.colors.primaryButtonText);
    // document.documentElement.style.setProperty('--custom-input-bg-color', state.theme.colors.inputBgColor);
    // document.documentElement.style.setProperty('--custom-input-color', state.theme.colors.inputColor);

  }, [state.theme]);
  /**
   * Function to get Ldap users
   * @returns 
   */

  const loggedUser = () => {
    return fetch('http://localhost:3800/users/logged-user', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw message.warning("Client application not running");
        }
        return response.json();
      })
      .then((data) => {
        if (data && data.success) {
          return data.username;
        } else {
          message.warning("Client application not running");
        }
      })
      .catch((error) => {
        console.log(error);
        message.warning("Client application not running");
        setLdapLoading(false);
        return null;
      });
  };





  /**
   * 
   * @returns Function to login with ldap
   * 
   */
  const loginWithLdap = async () => {

    //call function to get the current logged username
    const username = await loggedUser();


    //formbody consist of username from loggeduser
    let formBody = {
      username: username
    }
    //calling ldap-login API
    return ApiUtils.post({
      // url: "users/logged-user",
      url: "auth/ldap-login",
      formBody,
      headers,


    }).then((result) => {


      setLdapLoading(false);

      const { user, access_token } = result;

      localStorage.access_token = access_token;

      if (result.success) {

        //two_factor_authentication variable is present then proceed Two factor authentication
        if (result.data && result.data.two_factor_authentication) {
          let data;

          // set variable used for otp send screen
          setOtpVisible(true);

          // set user credentials
          data = {
            username: result.data.email,
            password: values.password,
            mode: result.data.mode ? result.data.mode : null,
            mobile: result.data.mobile ? result.data.mobile : null
          };

          // set user values
          setUser(data);

        } else {
          let d = user;

          let userInfo = {
            id: user.id,
            locations: [],
            ...d,
            ...{
              loggedCheckDone: true,
            },
          };

          dispatch({ type: "user", payload: userInfo });

          localStorage.setItem("userInfo", JSON.stringify(userInfo));

          history.push("/");
        }
      } else {
        message.error(result.message);
      }
    })
      .catch((error) => {
        console.log(error);

        message.error("This operation has failed.");

        setLdapLoading(false);
      });

  }

 
 


  const { globalCustomerHeader = () => { } } = appSettings;

  return (
    <section className="full-page" 
    style={{ 
      backgroundColor: state.theme.colors.loginPageBackground,
      backgroundImage: `url(${backgroundImage})`,
      background:  `url(${backgroundImage}) no-repeat bottom  center, ${state.theme.colors.loginPageBackground}`
      //  background:  state.theme.colors.loginPageBackground
    }}>
    
      <section className="user-authentication-section">
        {/* Background Section */}
        <motion.div className="page-background"
          
          initial={{ y: -50, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ duration: 1, ease: "anticipate" }}
          exit={{ opacity: 0 }}
        ></motion.div>
        {/* Background Section Ends */}

        <motion.div className="auth-form-wrapper"
          initial={{ y: 20 }}
          animate={{ y: 0 }}
          transition={{ duration: 1, ease: "anticipate" }}
          exit={{ opacity: 0 }}
        >
          <div className="card card-shadow login-form-container"
            style={{ background: state.theme.colors.tableBg, borderStyle: state.theme.colors.tableBorderStyle }}>
            <div className="brand-logo">
              <img className="logo-welcome" src={brandLogo} alt="Logo" />
            </div>

            <div className="otp-form">
              {/* Two factor authentication section start */}
              {otpVerification ? (
                <div className="otp-input-container">
                  <div className="form-title">
                    <h3>Verify your account</h3>
                    <p>
                      An OTP has been sent to your Email<br></br>
                    </p>
                  </div>
                  <p className="otp-title">ENTER OTP</p>
                  <div className="otp-container">
                    <OTPInput
                      value={otpValue}
                      onChange={handleOtpChange}
                      autoFocus
                      OTPLength={6}
                    />
                  </div>
                  <Button
                    type="primary"
                    className="SubmitBtn"
                    onClick={verifyOtp}
                  >
                    <i className="fa-regular fa-circle-check"></i> Verify
                    OTP
                  </Button>
                  <Link className="resend-otp-link" onClick={handleResendOTP}>
                    <i className="fa-solid fa-arrows-rotate"></i> Resend
                    OTP
                  </Link>
                  {/* Two factor authentication section end */}
                </div>
              ) : otpVisible ? (
                <div className="otp-input-container">
                  {/* Two factor authentication otp verification section start  */}
                  <div className="form-title">
                    <h4>Two Factor Authentication</h4>
                    <p>
                      Two-Factor Authentication is enabled for your account . Please verify your account before your login to enhance the security of your account.
                      <br></br>
                    </p>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  </div>

                  <div className="otp-container">
                    <Button
                      type="primary"
                      className="SubmitBtn"
                      onClick={sendAuthenticationOtp}
                      loading={loading}
                    >
                      Send OTP
                    </Button>
                    <Button

                      type="secondary"

                      onClick={handlecancel}>Cancel</Button>
                  </div>
                  {/* Two factor authentication otp verification section end  */}
                </div>
              ) : (
                <>

                  <Form
                    {...layout}
                    layout="vertical"
                    name="basic"
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}

                  >
                    <div className="form-title">
                      <h4></h4>
                      {/* <p>Your work assistant for the day!</p> */}
                    </div>

                    {/** branchswitcher Option  */}
                    <div className="branch-switcher">{globalCustomerHeader()}</div>


                    {/* {heroImage && (
                      <img className="customers" src={heroImage} alt="Logo" />
                    )} */}

                    <br></br><div>

                      {process.env.REACT_APP_ENABLE_LDAP == "true" && (
                        <Button
                          loading={ldaploading}
                          type="secondary"

                          className="SubmitBtn"
                          onClick={loginWithLdap
                          }
                        >

                          Sign in using AD
                        </Button>
                      )}
                    </div>
                    <Form.Item
                      label="Email"
                      name="email"
                      rules={[
                        { required: true, message: "Please input your email!" },
                      ]}
                    >
                      <Input autoComplete="off" />
                    </Form.Item>

                    <Form.Item
                      label="Password"
                      name="password"
                      rules={[
                        { required: true, message: "Please input your password!" },
                      ]}
                    >
                      <Input.Password autoComplete="off" />
                    </Form.Item>


                    <Form.Item {...tailLayout}>
                      <Button
                        loading={loading}
                        type="primary"
                        htmlType="submit"
                        className="SubmitBtn"
                      >
                        {/* <FontAwesomeIcon icon={faCheck} /> */}
                        &nbsp;&nbsp;
                        {/* <span>
                      <img src="../assets/tick-icon.png" alt="Tick Icon" />
                    </span> */}
                        Submit
                      </Button>
                    </Form.Item>
                  </Form>

                </>
              )}

            </div>
          </div>

          {/* <div className="center-line"> */}
          {/* <Link to="/register">Create Account</Link> */}
          {/* <img className="footer-logo" src={footerLogo} alt={'user photograph'} /> */}
          {/* </div> */}

          {/* {heroImage && <img className="customers2" src={heroImage} alt="Logo" />} */}
        </motion.div>
      </section>

    </section>
  );
}

export default withRouter(LoginPhone);
