import React, { useEffect, useRef, useState } from "react";
import "../../App.css";
import Footer from "../../Footer";
import InputField from "../InputField";
import SubmitField from "../SubmitField";
import ErrorMessage from "../ErrorMessage";
import { Logger } from "@behametrics/logger-web";
import { Button } from "../Button";
import BehaviorStudyInfo from "../BehaviorStudyInfo";
import BehaviorNormal from "../BehaviorNormal";
import BehaviorPhone from "../BehaviorPhone";
import BehaviorStanding from "../BehaviorStanding";
import BehaviorStudyEnd from "../BehaviorStudyEnd";
import { authFetch } from "../../auth/AuthProvider";
import StudyFinished from "../StudyFinished";

export default function Study() {
  const _logger = useRef(0);
  const [serverUsername, setServerUsername] = useState("");
  const [genPassword, setGenPassword] = useState("");
  const STATES = {
    START: "start",
    NORMAL: "normal",
    PHONE: "phone",
    STANDING: "standing",
    END: "end",
  };
  const [state, setState] = useState(STATES.START);
  const [isInputCorrect, setIsInputCorrect] = useState(true);

  const errorText =
    "Das Passwort und der Benutzername stimmen nicht überein. Bitte prüfen Sie, dass Sie das Passwort richtig abgetippt und den Benutzernamen richtig eingegeben haben.";

  useEffect(() => {
    _logger.current = new Logger({
      inputs: ["keyboard", "wheel", "cursor", "custom"],
    });
    _logger.current.init();
    authFetch("/api/username", {
      method: "get",
    }).then((response) => {
      response.json().then((resp) => {
        setServerUsername(resp.username);
      });
    });
  }, []);

  let username = "";
  const setUsername = (tmp_username) => {
    username = tmp_username;
  };

  let password = "";
  const setPassword = (tmp_password) => {
    password = tmp_password;
  };

  const handleLoggerOff = () => {
    _logger.current.stop();
    console.log("Logger ausgeschaltet");
  };

  const handleLoggerOn = () => {
    _logger.current.start();
    console.log("start logging ");
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleUsernameChange = (e) => {
    setUsername(e.target.value);
  };

  const handleOnPasteEvent = (e) => {
    e.preventDefault();
    return false;
  };
  const handleOnCopyEvent = (e) => {
    e.preventDefault();
    return false;
  };

  const checkIfUsernameIsCorrect = () => {
    return serverUsername === username;
  };

  const receiveRandomPassword = () => {
    fetch("/api/rcv_pw", {
      method: "get",
    }).then((response) => {
      response.json().then((resp) => {
        setGenPassword(resp.random_password);
      });
    });
  };

  const checkIfPasswordIsCorrect = () => {
    return genPassword === password;
  };

  const checkIfValuesAreCorrect = () => {
    return checkIfPasswordIsCorrect() && checkIfUsernameIsCorrect();
  };

  const handleClickAtStepStart = () => {
    receiveRandomPassword();
    setState(STATES.NORMAL);
    handleLoggerOn();
    // map username and session with the logs
    _logger.current.logCustomEvent({
      name: serverUsername,
    });
  };

  const resetInputValues = () => {
    let inputElements = document.querySelectorAll(
      'div input:not([type="submit"])'
    );
    for (let i = 0; i < inputElements.length; i++) {
      inputElements[i].value = "";
    }
  };

  const handleClickAtStepNormal = () => {
    if (checkIfValuesAreCorrect()) {
      receiveRandomPassword();
      setIsInputCorrect(true);
      setState(STATES.PHONE);
    } else {
      setIsInputCorrect(false);
      resetInputValues();
    }
  };

  const handleClickAtStepPhone = () => {
    if (checkIfValuesAreCorrect()) {
      receiveRandomPassword();
      setIsInputCorrect(true);
      setState(STATES.STANDING);
    } else {
      setIsInputCorrect(false);
      resetInputValues();
    }
  };

  const handleClickAtStepStanding = () => {
    if (checkIfValuesAreCorrect()) {
      setIsInputCorrect(true);
      setState(STATES.END);
      handleLoggerOff();
    } else {
      setIsInputCorrect(false);
      resetInputValues();
    }
  };

  const study_start = (
    <>
      <BehaviorStudyInfo />
      <Button
        className="btns"
        buttonStyle="btn--primary"
        buttonSize="btn--full"
        onClick={handleClickAtStepStart}
        newTo="study"
      >
        Studie starten
      </Button>
    </>
  );

  const study_normal = (
    <>
      <BehaviorNormal onCopy={handleOnCopyEvent} genPassword={genPassword} />
      {!isInputCorrect && <ErrorMessage message={errorText} />}
      <div>
        <InputField
          LabelName="Benutzername"
          onChange={handleUsernameChange}
          InputType="text"
          InputName="Benutzername"
          InputPlaceHolder="Benutzername"
          onPaste={handleOnPasteEvent}
        />
        <InputField
          LabelName="Passwort"
          onChange={handlePasswordChange}
          InputType="password"
          InputName="Passwort"
          InputPlaceHolder="Passwort"
          onPaste={handleOnPasteEvent}
        />
        <SubmitField
          LabelName="Weiter zur nächsten Situation"
          InputValue="next-situation"
          InputName="Weiter"
          onClick={handleClickAtStepNormal}
        />
      </div>
    </>
  );

  const study_phone = (
    <>
      <BehaviorPhone genPassword={genPassword} />
      {!isInputCorrect && <ErrorMessage message={errorText} />}
      <div>
        <InputField
          LabelName="Benutzername"
          onChange={handleUsernameChange}
          InputType="text"
          InputName="Benutzername"
          InputPlaceHolder="Benutzername"
          onPaste={handleOnPasteEvent}
        />
        <InputField
          LabelName="Passwort"
          onChange={handlePasswordChange}
          InputType="password"
          InputName="Passwort"
          InputPlaceHolder="Passwort"
          onPaste={handleOnPasteEvent}
        />
        <SubmitField
          LabelName="Weiter zur nächsten Situation"
          InputValue="next-situation"
          InputName="Weiter"
          onClick={handleClickAtStepPhone}
        />
      </div>
    </>
  );

  const study_standing = (
    <>
      <BehaviorStanding genPassword={genPassword} />
      {!isInputCorrect && <ErrorMessage message={errorText} />}
      <div>
        <InputField
          LabelName="Benutzername"
          onChange={handleUsernameChange}
          InputType="text"
          InputName="Benutzername"
          InputPlaceHolder="Benutzername"
          onPaste={handleOnPasteEvent}
        />
        <InputField
          LabelName="Passwort"
          onChange={handlePasswordChange}
          InputType="password"
          InputName="Passwort"
          InputPlaceHolder="Passwort"
          onPaste={handleOnPasteEvent}
        />
        <SubmitField
          LabelName="Studie beenden"
          InputValue="stopStudy"
          InputName="quit"
          onClick={handleClickAtStepStanding}
        />
      </div>
    </>
  );

  const study_end = <BehaviorStudyEnd />;

  return (
    <>
      <div className="sitePage">
        <h1>Studie</h1>
        <StudyFinished />
        {state === STATES.START ? study_start : null}
        {state === STATES.NORMAL ? study_normal : null}
        {state === STATES.PHONE ? study_phone : null}
        {state === STATES.STANDING ? study_standing : null}
        {state === STATES.END ? study_end : null}
      </div>
      <Footer />
    </>
  );
}
