<script setup>
import { SelectBox } from 'tedir-select'

const props = defineProps({
  modelValue: Object
})

const emit = defineEmits(['update:modelValue', 'save'])

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const clientName = ref('')
onMounted(() => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
})

const form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue?.uid || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  name: props.modelValue.name || '',
  description: props.modelValue.description || '',
  sendDunningLetter: props.modelValue.sendDunningLetter ?? false,
  isActive: props.modelValue.isActive ?? true,
  isDefault: props.modelValue.isDefault ?? false,
  createLevelsSequentially: props.modelValue.createLevelsSequentially ?? false,
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false
  }
})

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    /*if(key === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }*/
    
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

watch(() => props.modelValue, () => {
  form.value = props.modelValue
})

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const save = debounce(() => {
  //form.value.alert.processing = true
  emit('update:modelValue', form.value)
  emit('save', form.value)
  /*if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id)
  } else {
    emit('save', form.value, '')
  }*/
})
</script>

<template>
  <div @mouseleave.self="save">
    <div class="row m-3 mt-0">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <div class="columns is-desktop">
        <div class="column is-two-thirds">
          <div class="legend">
            <label class="label">Name *</label>
            <input type="text" v-model="form.name" class="input" @keyup="save" />
          </div>

          <div class="legend mt-2">
            <label class="label">Description</label>
            <textarea v-model="form.description" class="input" @keyup="save"></textarea>
          </div>

          <label class="label d-block mt-2 mb-2">Properties</label>
          <div class="d-flex flexDirection-column">
            <div class="check">
              <input type="checkbox" v-model="form.sendDunningLetter" class="checkInput" id="sendDunningLetter" :checked="form.sendDunningLetter" @change="save">
              <label class="checkLabel" for="sendDunningLetter">Send Dunning Letter</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.createLevelsSequentially" class="checkInput" id="createLevelsSequentially" :checked="form.createLevelsSequentially" @change="save">
              <label class="checkLabel" for="createLevelsSequentially">Create Levels Sequentially</label>
            </div>
          </div>
        </div>
        <div class="column is-one-third">
          <div class="legend">
            <label class="label">Organization *</label>
            <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {form.organization = opt.Name; save();}" :loading="loading?.['orgs'] ?? true" />
          </div>

          <div class="legend mt-2">
            <label class="label">Tenant *</label>
            <input type="text" class="input is-normal" :value="clientName" readonly />
          </div>

          <label class="label d-block mt-2 mb-2">Status</label>
          <div class="d-flex flexDirection-column">
            <div class="check">
              <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" @change="save">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isDefault" class="checkInput" id="isDefault" :checked="form.isDefault" @change="save">
              <label class="checkLabel" for="isDefault">Default</label>
            </div>
          </div>

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