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

const router = useRouter()

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

const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  name: '',
  description: '',
  help: '',
  isActive: true,
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const back = () => {
  router.push('/partners/job-categories')
}

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

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

  const res = await $fetch('/api/partners/job-categories/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      name: form.value.name,
      description: form.value.description,
      help: form.value.help,
      isActive: form.value.isActive
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/partners/job-categories/' + res.id + '/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/partners/job-categories/'+res.id+'/edit')
      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
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
  }
}

const breadCrumb = computed(() => ([
  { link: '/partners/partners', text: 'Partners'},
  { link: '/partners/job-categories', text: 'Job Categories'},
  { link: '#', text: 'Add Job Category', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Job Category</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>
      <div class="banner">
        <div>
          <PartnersJobCategoryForm v-model="form" @save="save"/>
        </div>
      </div>

    </div>
  </NuxtLayout>
</template>