<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'

const router = useRouter()
const route = useRoute()
const activeSave = useActiveSave()
const tabs = useTabs()

definePageMeta({
  middleware: ['auth', 'org']
})

const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')

const form = ref({
  id: '',
  uid: '',
  isActive: true,
  name: '',
  description: '',
  value: '',
  isSummary: false,
  tenant: client.value?.Name || '',
  tenantId: clientId.value || '',
  replicationStrategy: '',
  replicationStrategyId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/admin/organizations/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: '',
      uid: '',
      isActive: res?.IsActive ?? true,
      name: res?.Name || '',
      description: res?.Description || '',
      value: res?.Value || '',
      isSummary: res?.IsSummary ?? false,
      tenant: res?.AD_Client_ID?.identifier || '',
      tenantId: res?.AD_Client_ID?.id || '',
      replicationStrategy: res?.AD_ReplicationStrategy_ID?.identifier || '',
      replicationStrategyId: res?.AD_ReplicationStrategy_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }

    setActiveSave()
  }
}
onMounted(retrieve)

const setActiveSave = () => {
  if(form.value.name !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === comparePath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === comparePath)
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = toPath
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    //router.push('/users/organizations')
    openTab(`/users/organizations`, `Organizations`)
  }
}

const save = async (record) => {
  form.value = record
  
  setActiveSave()
}

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/admin/organizations/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      tenantId: form.value.tenantId,
      isActive: form.value.isActive,
      name: form.value.name,
      description: form.value.description,
      value: form.value.value,
      isSummary: form.value.isSummary,
      replicationStrategyId: form.value.replicationStrategyId,
    }
  })

  if(Number(res.status) === 200 && res.id) {
    /*for(let [key, items] of Object.entries(entries)) {
      for(let entry of items) {
        if(entry.id) {
          let body = {}
          if(key === 'organization_info') {
            body = {
              id: entry.id,
              isActive: entry.isActive,
              DUNS: body.DUNS,
              taxID: body.taxID,
              locationId: entry.locationId,
              warehouseId: entry.warehouseId,
              orgTypeId: entry.orgTypeId,
              supervisorId: entry.supervisorId,
              parentOrgId: entry.parentOrgId,
            }
          }

          await $fetch(`/api/admin/organizations/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'PUT',
            headers: useRequestHeaders(['cookie']),
            body
          })
        } else {
          let body = {}
          if(key === 'organization_info') {
            body = {
              isActive: entry.isActive,
              DUNS: body.DUNS,
              taxID: body.taxID,
              locationId: entry.locationId,
              warehouseId: entry.warehouseId,
              orgTypeId: entry.orgTypeId,
              supervisorId: entry.supervisorId,
              parentOrgId: entry.parentOrgId,
            }
          }

          await $fetch(`/api/admin/organizations/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'POST',
            headers: useRequestHeaders(['cookie']),
            body
          })
        }
      }
    }*/
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      //router.push('/users/organizations/'+res.id+'/view')
      openTab(`/view/organization-${res.id}`, `Organization: View Details`)
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      //router.push('/users/organizations/'+res.id+'/edit')
      openTab(`/edit/organization-${res.id}`, `Organization: ${res.Name}`)
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      back()
    }
  } else {
    form.value.alert.status = res.status
    form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = false
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '/users/users', text: 'Users'},
  { link: '/users/organizations', text: 'Organizations'},
  { link: '#', text: 'Add Organization', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Organization</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    
    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" @click="submit('onlysave')" class="button" :class="(form.name === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
      </div>
      <div>
        <div class="d-flex gap-10px">
          <button v-if="activeSave" type="button" @click="activeSave = false; back();" class="button">
            <span class="tf-icon ti ti-square-x ti-xs me-1 color-inherit"></span> Abort
          </button>
          <button type="button" @click="back" class="button">
            <span class="tf-icon ti ti-chevron-left ti-xs me-1 color-inherit"></span> Back
          </button>
        </div>
      </div>
    </div>

    <div class="banner">
      <div>
        <AdminOrganizationForm v-model="form" @save="save"/>
      </div>
    </div>
  </NuxtLayout>
</template>