<script setup>
/*definePageMeta({
  middleware: ['guest']
})*/


const router = useRouter()
const idempiereUsername = useCookie('logship_xu', {default: () => '', watch: 'shallow'})
const idempierePassword = useCookie('logship_py', {default: () => '', watch: 'shallow'})
const idempiereToken = useCookie('logship_it', {default: () => '', watch: 'shallow'})
const idempiereRefreshToken = useCookie('logship_rt', {default: () => '', watch: 'shallow'})
const idempiereRememberMe = useCookie('logship_rm', {default: () => 0, watch: 'shallow'})
const idempiereSelectRole = useCookie('logship_sr', {default: () => 0, watch: 'shallow'})

const idempiereClients = useCookie('logship_clients', {default: () => [], watch: 'shallow'})
const idempiereClient = useCookie('logship_client', {default: () => null, watch: 'shallow'})
const idempiereClientId = useCookie('logship_client_id', {default: () => '', watch: 'shallow'})

const idempiereOrganizations = useCookie('logship_organizations', {default: () => [], watch: 'shallow'})
const idempiereOrganization = useCookie('logship_organization', {default: () => null, watch: 'shallow'})
const idempiereOrganizationId = useCookie('logship_organization_id', {default: () => '', watch: 'shallow'})

const idempiereRoles = useCookie('logship_roles', {default: () => [], watch: 'shallow'})
const idempiereRole = useCookie('logship_role', {default: () => null, watch: 'shallow'})
const idempiereRoleId = useCookie('logship_role_id', {default: () => '', watch: 'shallow'})

const idempiereWarehouses = useCookie('logship_warehouses', {default: () => [], watch: 'shallow'})
const idempiereWarehouse = useCookie('logship_warehouse', {default: () => null, watch: 'shallow'})
const idempiereWarehouseId = useCookie('logship_warehouse_id', {default: () => '', watch: 'shallow'})

const idempiereUser = useCookie('logship_user', {default: () => null, watch: 'shallow'})
const idempiereUserId = useCookie('logship_user_id', {default: () => '', watch: 'shallow'})

const idempiereLanguage = useCookie('logship_language', {default: () => 'en_US', watch: 'shallow'})
const logshipSession = useCookie('logship_session', {
  default: () => '',
  watch: 'shallow'
})

const form = reactive({
  userName: '',
  password: '',
  remember: false,
  selectRole: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})



watch(idempiereRememberMe, () => {
  if(Number(idempiereRememberMe.value || 0)) {
    form.userName = atob(idempiereUsername.value || '')
    form.password = atob(idempierePassword.value || '')
  }
})

onMounted(() => {
  if(Number(idempiereRememberMe.value || 0)) {
    form.userName = atob(idempiereUsername.value || '')
    form.password = atob(idempierePassword.value || '')
  }
})

const showPassword = ref(false)

const submit = async () => {
  form.alert.processing = true
  form.alert.status = '' // Clear previous alerts
  form.alert.message = ''

  try {
    const getIdempiereUsername = localStorage.getItem('idempiere_username')
    if(getIdempiereUsername !== form.userName) {
      localStorage.setItem('idempiere_username', form.userName)
      form.selectRole = true
    }

    const data = await $fetch('/api/idempiere-auth/login', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        userName: form.userName,
        password: form.password,
        remember: form.remember,
        selectRole: form.selectRole
      }
    })

    if(data?.status && data?.message) {
      form.alert.status = data.status
      form.alert.message = data.message
    } else {
      if(data.token) {
        idempiereToken.value = data.token
      }

      if(data.session) {
        logshipSession.value = data.session
      }

      if(data.clients) {
        idempiereClients.value = data.clients
        localStorage.setItem('logship_clients', JSON.stringify(data.clients))
      }

      if(data?.toDashboard || idempiereClientId.value || idempiereRoleId.value) {
        idempiereUser.value = data?.user || null
        idempiereClient.value = data?.client || null
        idempiereOrganization.value = data?.organization || null
        idempiereRole.value = data?.role || null
        idempiereWarehouse.value = data?.warehouse || null

        if(form.selectRole) {
          router.push('/select-role')
        } else {
          router.push('/')
        }
      } else {
        router.push('/select-role')
      }
    }

    idempiereUsername.value = btoa(form.userName)
    idempierePassword.value = btoa(form.password)
    idempiereRememberMe.value = form.remember ? 1 : 0
    idempiereSelectRole.value = form.selectRole ? 1 : 0

  } catch (error) {
    // Handle different types of errors
    if (error.status === 401 || error.statusCode === 401) {
      form.alert.status = 'Login Failed'
      form.alert.message = 'Wrong username or password entered. Please check your credentials and try again.'
    } else if (error.status === 500 || error.statusCode === 500) {
      form.alert.status = 'Server Error'
      form.alert.message = 'There was a problem with the server. Please try again later.'
    } else if (error.status === 0 || !error.status) {
      form.alert.status = 'Connection Error'
      form.alert.message = 'Unable to connect to the server. Please check your internet connection.'
    } else {
      form.alert.status = 'Error'
      form.alert.message = 'An unexpected error occurred. Please try again.'
    }
  }

  form.alert.processing = false
}
</script>

<template>
  <NuxtLayout name="new-auth">
    <div class="login">
      <form @submit.prevent="submit">
        <div class="logo">
<!--          <span>-->
<!--            <svg width="32" height="22" viewBox="0 0 32 22" fill="none" xmlns="http://www.w3.org/2000/svg">-->
<!--              <path-->
<!--                fill-rule="evenodd"-->
<!--                clip-rule="evenodd"-->
<!--                d="M0.00172773 0V6.85398C0.00172773 6.85398 -0.133178 9.01207 1.98092 10.8388L13.6912 21.9964L19.7809 21.9181L18.8042 9.88248L16.4951 7.17289L9.23799 0H0.00172773Z"-->
<!--                fill="#7367F0" />-->
<!--              <path-->
<!--                opacity="0.06"-->
<!--                fill-rule="evenodd"-->
<!--                clip-rule="evenodd"-->
<!--                d="M7.69824 16.4364L12.5199 3.23696L16.5541 7.25596L7.69824 16.4364Z"-->
<!--                fill="#161616" />-->
<!--              <path-->
<!--                opacity="0.06"-->
<!--                fill-rule="evenodd"-->
<!--                clip-rule="evenodd"-->
<!--                d="M8.07751 15.9175L13.9419 4.63989L16.5849 7.28475L8.07751 15.9175Z"-->
<!--                fill="#161616" />-->
<!--              <path-->
<!--                fill-rule="evenodd"-->
<!--                clip-rule="evenodd"-->
<!--                d="M7.77295 16.3566L23.6563 0H32V6.88383C32 6.88383 31.8262 9.17836 30.6591 10.4057L19.7824 22H13.6938L7.77295 16.3566Z"-->
<!--                fill="#7367F0" />-->
<!--            </svg>-->
<!--          </span>-->
<!--          <span class="ms-1 "></span>-->
        <div class="loginlogo"></div>
        <div class="editionname">3PL</div>

        </div>
<!--        <h3>Willkomen</h3>-->

        
        <div v-if="form.alert.status" class="alert alert-danger">
          <div class="alertContent">
            <h3 class="alertTitle">{{ form.alert.status }}</h3>
            <p class="alertText">{{ form.alert.message }}</p>
          </div>
          <!--<div class="alertAction">X</div>-->
        </div>
<!--        <h5 v-else>-->
<!--          Today is a new day. It's your day. You shape it. Sign in to start-->
<!--          manageing your products-->
<!--        </h5>-->

        <label for="email">Username <span>*</span></label>
        <input type="text" v-model="form.userName" id="email" name="email" required placeholder="Enter your Username!" autofocus />

        <label for="password">Password <span>*</span></label>
        <div class="pi-relative">
          <input :type="showPassword ? 'text' : 'password'" v-model="form.password" id="password" name="password" required :placeholder="showPassword ? 'Enter your Password!' : '&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;'" class="w-100pct" />
          <UTooltip text="Toggle password visibility" :shortcuts="['Alt', 'P']">
            <span class="pi-absolute right-10px top-15pct" @click="showPassword = !showPassword"><i :class="`ti ti-eye${showPassword ? '-off' : ''}`"></i></span>
          </UTooltip>
        </div>

        <div class="remember__area">
          <label for="selectRole" class="remember">
            <input type="checkbox" v-model="form.selectRole" name="selectRole" id="selectRole" />

            <UTooltip text="Wählen Sie Ihre Firma und Lager aus" placement="right">
              <p>Auswahl anzeigen <i class="ti ti-info-circle"></i></p>
            </UTooltip>
          </label>

          
        </div>

        <div class="remember__area">
          <label for="remember" class="remember">
            <input type="checkbox" v-model="form.remember" name="remember" id="remember" />

            <UTooltip text="Speichert Ihre Login-Auswahl">
              <p>Quick Login <i class="ti ti-info-circle"></i></p>
            </UTooltip>
          </label>

<!--          <NuxtLink to="/forgot-password">-->
<!--            <p class="forgot">Forgot Password?</p>-->
<!--          </NuxtLink>-->
        </div>

        <input type="submit" value="Login" class="submit__button" />

<!--        <div class="or">-->
<!--          <div class="line"></div>-->
<!--          Or-->
<!--          <div class="line"></div>-->
<!--        </div>-->

<!--        <button class=" ">-->
<!--          <img src="/assets/google.png" alt="google" />-->
<!--          Sign in with Google-->
<!--        </button>-->

<!--        <button class="facebook">-->
<!--          <img src="/assets/facebook.webp" alt="facebook" />-->
<!--          Sign in with Facebook-->
<!--        </button>-->


<!--        <div class="sign__up">-->
<!--          Don't have an account? <NuxtLink to="/register">Sign up</NuxtLink>-->
<!--        </div>-->
      </form>
    </div>
  </NuxtLayout>
</template>

<style scoped>
@ref pi-relative pi-absolute right-10px top-25pct w-100pct;

.loginlogo {
  background: url(/assets/logo-white.png);
  background-size: 150px;
  width: 100%;
  height: 100px;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background-repeat: no-repeat;
  background-position: center;
  padding-left: 35%;
}



@media only screen and (max-width: 900px) {
  .login {
    padding-left: 0 !important;
  }
}

@media only screen and (min-width: 900px) {
.login {
  display: flex;
  justify-content: center;   /* horizontal centering */
  align-items: center;       /* vertical centering */
  /* ensure it has some height; e.g. full viewport: */
  min-height: 100vh;
}
.login form {
  height: auto;
  width: 41%;
  display: flex;
  flex-direction: column;
  background-color: #525252;
  box-shadow: rgba(100,100,111,0.2) 0px 7px 29px 0px;
  padding-top: 4%;
  border-radius: 3px;
  width: 23%;
  margin-top:-100px;
}

}

.editionname {
  color: orange !important;
  font-size: 23px;
  opacity: 0.8;
}
</style>