<script setup>
const config = useRuntimeConfig()

import { SelectBox } from 'tedir-select'
/*definePageMeta({
  middleware: ['guest']
})*/

const router = useRouter()
const idempiereClients = useCookie('logship_clients')
const idempiereClient = useCookie('logship_client')
const idempiereClientId = useCookie('logship_client_id')

const idempiereOrganizations = useCookie('logship_organizations')
const idempiereOrganization = useCookie('logship_organization')
const idempiereOrganizationId = useCookie('logship_organization_id')

const idempiereRoles = useCookie('logship_roles')
const idempiereRole = useCookie('logship_role')
const idempiereRoleId = useCookie('logship_role_id')

const idempiereWarehouses = useCookie('logship_warehouses')
const idempiereWarehouse = useCookie('logship_warehouse')
const idempiereWarehouseId = useCookie('logship_warehouse_id')

const idempiereUser = useCookie('logship_user')
const idempiereUserId = useCookie('logship_user_id')

const idempiereLanguage = useCookie('logship_language')
const idempiereRefreshToken = useCookie('logship_rt')

const form = reactive({
  clientId: '',
  roleId: '',
  organizationId: '',
  warehouseId: '',
  language: 'en_US',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const clients = ref(idempiereClients.value ?? [])
watch(idempiereClients, () => {
  clients.value = idempiereClients.value ?? []
})

const roles = ref(idempiereRoles.value ?? [])
watch(idempiereRoles, () => {
  roles.value = idempiereRoles.value ?? []
})

onMounted(() => {
  const getClients = localStorage.getItem('logship_clients')
  if(getClients) {
    clients.value = JSON.parse(getClients)
  }
  
  // Preset client field with first record
  if (clients.value && clients.value.length > 0) {
    form.clientId = String(clients.value[0].id)
    // Automatically load roles for the first client
    handleRole(form.clientId, clients.value[0])
  }
})

const languages = ref([{AD_Language: 'en_US'}])
const handleRole = async (val, opt) => {
  form.processing = true
  if(opt.id || form.clientId) {
    try {
      const res = await $fetch('/api/idempiere-auth/roles/'+(opt.id || form.clientId), {
        headers: useRequestHeaders(['cookie'])
      })
      if(res) {
        roles.value = res
        idempiereRoles.value = res
        
        // Auto-select first role after roles are loaded
        if (res.length > 0 && !form.roleId) {
          form.roleId = String(res[0].id)
          // Automatically load organizations for the first role
          handleOrganization(form.roleId, res[0])
        }
      }

      const resLang = await $fetch('/api/idempiere-auth/languages/'+(opt.id || form.clientId), {
        headers: useRequestHeaders(['cookie'])
      })
      if(resLang) {
        languages.value = resLang
        idempiereLanguage.value = resLang
      }
    } catch(error) {
      router.push('/signin')
    }
  } else {
    roles.value = []
    languages.value = []
  }
  form.processing = false
}

const organizations = ref(idempiereOrganizations.value ?? [])
watch(idempiereOrganizations, () => {
  organizations.value = idempiereOrganizations.value ?? []
})
const handleOrganization = async (val, opt) => {
  localStorage.setItem('idempiere_role', JSON.stringify(opt))
  form.processing = true
  if(opt.id || (form.clientId && form.roleId)) {
    try {
      const res = await $fetch('/api/idempiere-auth/organizations/'+form.clientId+'/'+(opt.id || form.roleId), {
        headers: useRequestHeaders(['cookie'])
      })
      if(res) {
        organizations.value = res
        idempiereOrganizations.value = res
      }
    } catch(error) {
      router.push('/signin')
    }
  } else {
    organizations.value = []
  }
  form.processing = false
}

const warehouses = ref(idempiereWarehouses.value ?? [])
watch(idempiereWarehouses, () => {
  warehouses.value = idempiereWarehouses.value ?? []
})
const handleWarehouse = async (val, opt) => {
  form.processing = true
  if(opt.id || (form.clientId && form.roleId && form.organizationId)) {
    try {
      const res = await $fetch('/api/idempiere-auth/warehouses/'+form.clientId+'/'+form.roleId+'/'+(opt.id || form.organizationId), {
        headers: useRequestHeaders(['cookie'])
      })
      if(res) {
        warehouses.value = res
        idempiereWarehouses.value = res
      }
    } catch(error) {
      router.push('/signin')
    }
  } else {
    warehouses.value = []
  }
  form.processing = false
}

  const isFormValid = computed(() => {
  return !!form.clientId && !!form.roleId && !!form.organizationId && !!form.warehouseId;
  })

const submit = async () => {
  form.processing = true
  const data = await $fetch('/api/idempiere-auth/select-role', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      clientId: Number(form.clientId),
      roleId: Number(form.roleId),
      organizationId: Number(form.organizationId),
      warehouseId: Number(form.warehouseId),
      language: form.language
    }
  })

  if(data?.status && data?.message) {
    form.alert.status = data.status
    form.alert.message = data.message
  } else {
    form.userId = data.userId

    idempiereUser.value = data.user
    idempiereUserId.value = form.userId

    idempiereClient.value = data.client || null
    idempiereClientId.value = form.clientId

    idempiereOrganization.value = data.organization || null
    idempiereOrganizationId.value = form.organizationId

    idempiereRole.value = data.role || null
    idempiereRoleId.value = form.roleId

    idempiereWarehouse.value = data.warehouse || null
    idempiereWarehouseId.value = form.warehouseId

    idempiereLanguage.value = form.language

    router.push('/')
  }
  form.processing = false
}
</script>

<template>
  <NuxtLayout name="new-auth">
    <div class="login">
      <form :class="form.processing ? 'pointerEvents-none opacity-0.6' : ''" @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">{{ config.public.solutionname }}</span>
        </div>
        <h3>Select Role</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>
            <a href="/">Go to Dashboard anyway</a>
          </div>
          <!--<div class="alertAction">X</div>-->
        </div>
        <h5 v-else>Tenant and Role Selection</h5>

        <p>
          <label for="clientId">Tenant/Client <span>*</span></label>
          <SelectBox v-model="form.clientId" :options="clients" prop="name" dataprop="id" datatype="string" @change="handleRole" :size="5" />
        </p>

        <p>
          <label for="roleId">Role <span>*</span></label>
          <SelectBox v-model="form.roleId" :options="roles" prop="name" dataprop="id" datatype="string" @change="handleOrganization" :size="5" />
        </p>
        <p>
          <label for="organizationId">Organization<span>*</span></label>
          <SelectBox v-model="form.organizationId" :options="organizations" prop="name" dataprop="id" datatype="string" @change="handleWarehouse" :size="5" />
        </p>
        <p>
          <label for="warehouseId">Warehouse<span>*</span></label>
          <SelectBox v-model="form.warehouseId" :options="warehouses" prop="name" dataprop="id" datatype="string" :up="true" :size="5" />
        </p>
<!--        <p>-->
<!--          <label for="language">Language</label>-->
<!--          <SelectBox v-model="form.language" :options="languages" :up="true" prop="AD_Language" dataprop="AD_Language" datatype="string" :size="5" />-->
<!--        </p>-->
        
        <input type="submit" value="Sign-In" class="submit__button" :class="(!isFormValid || form.processing) ? 'pointerEvents-none opacity-0.6' : ''" :disabled="!isFormValid || form.processing" />
      </form>
    </div>
  </NuxtLayout>
</template>

<style >
.login form .picker .pickerWrap .select {
  padding: 8px !important;
  padding-left: 72px;
  padding-left: 14px !important;
}


@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%;
}

.login {
  display: block !important;
  padding-left: 35% !important;
}

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

</style>