<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 || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  isActive: props.modelValue.isActive ?? true,
  name: props.modelValue.name || '',
  account: props.modelValue.account ?? '',
  companyCode: props.modelValue.companyCode ?? '',
  license: props.modelValue.license ?? '',
  seqNo: props.modelValue.seqNo ?? '',
  taxProviderCfg: props.modelValue.taxProviderCfg ?? '',
  taxProviderCfgId: props.modelValue.taxProviderCfgId ?? '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || ''
  }
})

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 save = (saveType = '') => {
  form.value.processing = true
  emit('update:modelValue', form.value)
  if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id, saveType)
  } else {
    emit('save', form.value, '', saveType)
  }
}
</script>

<template>
  <form @submit.prevent="save">
    <div class="my-5 mx-5">
      <AlertAction v-model='form.alert.status' :alert="form.alert" />

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

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Tax Provider Configurations</label>
              <ClientOnly>
                <SelectBox v-model="form.taxProviderCfgId" :options="getOptions?.['tax_configurations']?.records || [{id: form.taxProviderCfgId, Name: form.taxProviderCfg}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_taxprovidercfg', 'tax_configurations')" :loading="loading?.['tax_configurations'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Sequence Number</label>
              <input type="text" v-model="form.seqNo" class="input" />
            </div>
          </div>
        
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Account</label>
              <input type="text" v-model="form.account" class="input" />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Company Code</label>
              <input type="text" v-model="form.companyCode" class="input" />
            </div>
          </div>
        
          <label class="label d-block mt-2">License</label>
          <textarea v-model="form.license" class="input"></textarea>
        </div>

        <div class="column is-one-third">
          <label class="label d-block">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" />

          <label class="label d-block mt-2">Tenant *</label>
          <input type="text" :value="clientName" class="input" readonly />

          <label class="label d-block mt-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">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="m-3">
      <div class="d-flex gap-10px">
        <button type="submit" class="button" :class="(form.name === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
        <button type="button" @click="save('preview')" class="button" :class="(form.name === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit &amp; Preview</button>
        <button type="button" @click="save('changes')" class="button" :class="(form.name === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save Changes</button>
      </div>
    </div>
  </form>
</template>