const serverUrl = 'http://localhost:3088/';
const emailInputEl = document.getElementById('email');
const passwordInputEl = document.getElementById('password');
const emailErrEl = document.getElementById('emailErrMsg');
const passwordErrEl = document.getElementById('passwordErrMsg');
const emailContainerEl = document.getElementById('emailBox');
const passwordContainerEl = document.getElementById('passwordBox');
const showPasswordChk = document.getElementById('showPassword');
const emailNextBtn = document.getElementById('emailNextBtn');
const renterEmailLink = document.getElementById('renterEmail');
const loginSubmitBtn = document.getElementById('loginSubmitBtn');

passwordContainerEl.style.display = 'none';
emailInputEl.focus();

function showPasswordBox() {
  const email = emailInputEl.value;
  if (validateEmailOrPhone()) {
    emailContainerEl.style.display = 'none';
    passwordContainerEl.style.display = 'block';
    document.getElementById('entered-email').innerHTML = email;
    passwordInputEl.focus();
    emailInputEl.classList.remove('error');
    emailErrEl.innerText = '';
  } else {
    emailInputEl.classList.add('error');
    emailErrEl.innerText = 'Please enter valid email or phone';
  }
}

function validateEmailOrPhone() {
  const value = emailInputEl.value.trim();
  const regx = /^[6-9]\d{9}$/;
  if (value.includes('@') || regx.test(value)) {
    return true;
  }
  return false;
}

function togglePassword() {
  const ele = document.getElementById('showPassword');
  const password = passwordInputEl;

  if (password.value.length > 0) {
    passwordInputEl.value = password.value;
    password.focus();
    if (ele.checked) {
      password.setAttribute('type', 'text');
    } else {
      password.setAttribute('type', 'password');
    }
  }
}

function onPasswordFocusOut() {
  const passwordLabel = document.getElementById('passwordLabel');
  if (passwordInputEl.value.length > 0) {
    passwordLabel.classList.add('password-fixed');
  } else {
    passwordLabel.classList.remove('password-fixed');
  }
}

function onEmailFocusOut() {
  const emailLabel = document.getElementById('emailLabel');
  if (emailInputEl.value.trim()) {
    emailLabel.classList.add('password-fixed');
  } else {
    emailLabel.classList.remove('password-fixed');
  }
}

function setCookie(name, value, days) {
  var expires = '';
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    expires = '; expires=' + date.toUTCString();
  }
  document.cookie = name + '=' + (value || '') + expires + '; path=/';
}

function loginUser(email, password) {
  const postData = JSON.stringify({
    UserName: email,
    Password: password,
    UnibaseId: '',
    RememberMe: false,
  });

  const requestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: postData,
    redirect: 'follow',
  };

  fetch(serverUrl + 'account/login', requestOptions)
    .then((response) => response.text())
    .then((result) => {
      const data = JSON.parse(result);
      if (data.status === 0) {
        setCookie('authentication', data.result.sessionId, 1);
        window.location = '../authentication';
      } else {
        passwordErrEl.innerText = data.message;
      }
    })
    .catch((error) => {
      passwordErrEl.innerText = error;
    });
}

function validateLogin() {
  const email = emailInputEl.value;
  const password = passwordInputEl.value;
  if (password.trim().length !== 0) {
    loginUser(email, password);
  } else {
    passwordInputEl.classList.add('error');
    passwordErrEl.innerText = 'Please enter valid password';
  }
}

function reEnterEmailClickHandler() {
  emailContainerEl.style.display = 'block';
  passwordContainerEl.style.display = 'none';
  emailInputEl.focus();
}

function initializeEventListeners() {
  emailNextBtn.addEventListener('click', showPasswordBox);

  showPasswordChk.addEventListener('click', togglePassword);

  passwordInputEl.addEventListener('focusout', onPasswordFocusOut);

  emailInputEl.addEventListener('focusout', onEmailFocusOut);

  loginSubmitBtn.addEventListener('click', validateLogin);

  renterEmailLink.addEventListener('click', reEnterEmailClickHandler);
}

initializeEventListeners();
