<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 { data: currencies, pending, error, refresh } = await useFetch('/api/admin/currencies', {
  headers: useRequestHeaders(['cookie'])
})

const languages = useLanguages()

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 || '',
  name: props.modelValue.name || '',
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  countryCode: props.modelValue.countryCode || '',
  hasRegion: props.modelValue.hasRegion ?? true,
  displaySequence: props.modelValue.displaySequence || '@C@,  @P@',
  hasPostal_Add: props.modelValue.hasPostal_Add ?? false,
  isAddressLinesLocalReverse: props.modelValue.isAddressLinesLocalReverse ?? false,
  isAddressLinesReverse: props.modelValue.isAddressLinesReverse ?? false,
  isPostcodeLookup: props.modelValue.isPostcodeLookup ?? false,
  allowCitiesOutOfList: props.modelValue.allowCitiesOutOfList ?? false,
  captureSequence: props.modelValue.captureSequence || '@A1@ @A2@ @A3@ @A4@ @C@,  @P@ @CO@',
  currencyId: props.modelValue.currencyId || '',
  addressPrintFormat: props.modelValue.addressPrintFormat || '',
  localAddressFormat: props.modelValue.localAddressFormat || '',
  postalCodeFormat: props.modelValue.postalCodeFormat || '',
  phoneFormat: props.modelValue.phoneFormat || '',
  mediaSize: props.modelValue.mediaSize || '',
  bankRoutingNoFormat: props.modelValue.bankRoutingNoFormat || '',
  bankAccountNoFormat: props.modelValue.bankAccountNoFormat || '',
  language: props.modelValue.language || 'en_US',
  taxIDDigitGenerationClass: props.modelValue.taxIDDigitGenerationClass || '',
  placeholderForAddress1: props.modelValue.placeholderForAddress1 || '',
  placeholderForAddress2: props.modelValue.placeholderForAddress2 || '',
  placeholderForAddress3: props.modelValue.placeholderForAddress3 || '',
  placeholderForAddress4: props.modelValue.placeholderForAddress4 || '',
  placeholderForAddress5: props.modelValue.placeholderForAddress5 || '',
  placeholderForPostal: props.modelValue.placeholderForPostal || '',
  placeholderForAdditionalZip: props.modelValue.placeholderForAdditionalZip || '',
  placeholderForCity: props.modelValue.placeholderForCity || '',
  placeholderForComments: props.modelValue.placeholderForComments || '',
  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 = () => {
  form.value.processing = true
  emit('update:modelValue', form.value)
  if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id)
  } else {
    emit('save', form.value, '')
  }
}
</script>

<template>
  <form @submit.prevent="save">
    <div class="row m-3 mt-0">
      <div v-if="form.alert.status" class="col-md-12 mb-3">
        <div class="alert" :class="Number(form.alert.status) >= 400 ? 'alert-danger' : 'alert-success'">
          <div class="alertContent">
            <h3 class="alertTitle">{{ form.alert.status }}</h3>
            <p class="alertText">{{ form.alert.message }}</p>
          </div>
          <div class="alertAction" @click="form.alert.status = ''"><i class="menu-icon tf-icons ti ti-x"></i></div>
        </div>
      </div>

      <div class="col-md-6 mb-3">
        <label class="label">Tenant *</label>
        <input type="text" :value="clientName" class="input" readonly />
      </div>
      <div class="col-md-6 mb-3">
        <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="col-md-6 mb-3">
        <label class="label">ISO Country Code *</label>
        <input type="text" v-model="form.countryCode" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Name *</label>
        <input type="text" v-model="form.name" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Address Print Format *</label>
        <input type="text" v-model="form.addressPrintFormat" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Currency</label>
        <SelectBox v-model="form.currencyId" :options="currencies.records" prop="ISO_Code" dataprop="id" datatype="string" :size="5" />
      </div>
      <div class="col-md-12 mb-3">
        <label class="label">Description</label>
        <textarea v-model="form.description" class="input"></textarea>
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Local Address Format</label>
        <input type="text" v-model="form.localAddressFormat" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Postal Code Format</label>
        <input type="text" v-model="form.postalCodeFormat" class="input" />
      </div>
      <div class="col-md-12 mb-3">
        <label class="label d-block mb-2">Status</label>
        <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 class="check">
          <input type="checkbox" v-model="form.hasRegion" class="checkInput" id="hasRegion" :checked="form.hasRegion">
          <label class="checkLabel" for="hasRegion">Country has Region</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.hasPostal_Add" class="checkInput" id="hasPostal_Add" :checked="form.hasPostal_Add">
          <label class="checkLabel" for="isEmployee">Additional Postal code</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isAddressLinesReverse" class="checkInput" id="isAddressLinesReverse" :checked="form.isAddressLinesReverse">
          <label class="checkLabel" for="isAddressLinesReverse">Reverse Address Lines</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isAddressLinesLocalReverse" class="checkInput" id="isAddressLinesLocalReverse" :checked="form.isAddressLinesLocalReverse">
          <label class="checkLabel" for="isAddressLinesLocalReverse">Reverse Address Local Lines</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.isPostcodeLookup" class="checkInput" id="isPostcodeLookup" :checked="form.isPostcodeLookup">
          <label class="checkLabel" for="isPostcodeLookup">Use Postcode Lookup</label>
        </div>
        <div class="check">
          <input type="checkbox" v-model="form.allowCitiesOutOfList" class="checkInput" id="allowCitiesOutOfList" :checked="form.allowCitiesOutOfList">
          <label class="checkLabel" for="allowCitiesOutOfList">Allow Cities out of List</label>
        </div>
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Phone Format</label>
        <input type="text" v-model="form.phoneFormat" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Media Size</label>
        <input type="text" v-model="form.mediaSize" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Bank Routing No Format</label>
        <input type="text" v-model="form.bankRoutingNoFormat" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Bank Account No Format</label>
        <input type="text" v-model="form.bankAccountNoFormat" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Language</label>
        <SelectBox v-model="form.language" :options="languages" prop="text" dataprop="value" datatype="string" :size="5" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Tax ID Digit Generation Class</label>
        <input type="text" v-model="form.taxIDDigitGenerationClass" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for City</label>
        <input type="text" v-model="form.placeholderForCity" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Comments</label>
        <input type="text" v-model="form.placeholderForComments" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Postal</label>
        <input type="text" v-model="form.placeholderForPostal" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Additional Zip</label>
        <input type="text" v-model="form.placeholderForAdditionalZip" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Address 1</label>
        <input type="text" v-model="form.placeholderForAddress1" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Address 2</label>
        <input type="text" v-model="form.placeholderForAddress2" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Address 3</label>
        <input type="text" v-model="form.placeholderForAddress3" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Address 4</label>
        <input type="text" v-model="form.placeholderForAddress4" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Placeholder for Address 5</label>
        <input type="text" v-model="form.placeholderForAddress5" class="input" />
      </div>
    </div>
    <div class="row m-3">
      <div class="col-md-12 mb-3">
        <button type="submit" class="btn btn-primary waves-effect waves-light" :class="(form.name === '' || form.addressPrintFormat === '' || form.countryCode === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
      </div>
    </div>
  </form>
</template>