<script setup>
import { date } from 'alga-js'
import { SelectBox } from 'tedir-select'
import { DatePicker } from 'tedir-calendar'

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 || '',
  name: props.modelValue.name || '',
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  isDefault: props.modelValue.isDefault ?? false,
  isDocumentLevel: props.modelValue.isDocumentLevel ?? false,
  isSummary: props.modelValue.isSummary ?? false,
  isTaxExempt: props.modelValue.isTaxExempt ?? false,
  isSalesTax: props.modelValue.isSalesTax ?? false,
  validFrom: props.modelValue.validFrom || date.now('date'),
  rate: props.modelValue.rate || 6,
  requiresTaxCertificate: props.modelValue.requiresTaxCertificate ?? false,
  taxIndicator: props.modelValue.taxIndicator || '6%CT',
  countryGroup: props.modelValue.countryGroup || '',
  countryGroupId: props.modelValue.countryGroupId || '',
  country: props.modelValue.country || '',
  countryId: props.modelValue.countryId || '',
  region: props.modelValue.region || '',
  regionId: props.modelValue.regionId || '',
  toCountryGroup: props.modelValue.toCountryGroup || '',
  toCountryGroupId: props.modelValue.toCountryGroupId || '',
  toCountry: props.modelValue.toCountry || '',
  toCountryId: props.modelValue.toCountryId || '',
  toRegion: props.modelValue.toRegion || '',
  toRegionId: props.modelValue.toRegionId || '',
  taxCategory: props.modelValue.taxCategory || '',
  taxCategoryId: props.modelValue.taxCategoryId || '',
  SOPOType: props.modelValue.SOPOType || '',
  SOPOTypeId: props.modelValue.SOPOTypeId || '',
  taxPostingIndicator: props.modelValue.taxPostingIndicator || '',
  taxPostingIndicatorId: props.modelValue.taxPostingIndicatorId || '',
  taxProvider: props.modelValue.taxProvider || '',
  taxProviderId: props.modelValue.taxProviderId || '',
  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 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 Category *</label>
              <ClientOnly>
                <SelectBox v-model="form.taxCategoryId" :options="getOptions?.['tax_categories']?.records || [{id: form.taxCategoryId, Name: form.taxCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_taxcategory', 'tax_categories')" :loading="loading?.['tax_categories'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">Tax Provider</label>
              <ClientOnly>
                <SelectBox v-model="form.taxProviderId" :options="getOptions?.['tax_providers']?.records || [{id: form.taxProviderId, Name: form.taxProvider}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_taxprovider', 'tax_providers')" :loading="loading?.['tax_providers'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">SO/PO Type *</label>
              <select v-model="form.SOPOTypeId" class="select">
                <option value="B">Both</option>
                <option value="P">Purchase Tax</option>
                <option value="S">Sales Tax</option>
              </select>

              <label class="label d-block mt-2">Valid From *</label>
              <DatePicker v-model="form.validFrom" />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Rate *</label>
              <input type="text" v-model="form.rate" class="input" />
              
              <label class="label d-block mt-2">Tax Indicator</label>
              <input type="text" v-model="form.taxIndicator" class="input" />

              <label class="label d-block mt-2">Posting Indicator *</label>
              <select v-model="form.taxPostingIndicatorId" class="select">
                <option value="0">Separate Tax Posting</option>
                <option value="1">Distribute Tax with Relevant Expense</option>
              </select>
              
              <template v-if="!form.isSummary">
                <label class="label d-block mt-2">Parent Tax</label>
                <ClientOnly>
                  <SelectBox v-model="form.parentTaxId" :options="getOptions?.['parent_taxes']?.records || [{id: form.parentTaxId, Name: form.parentTax}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_tax', 'parent_taxes')" :loading="loading?.['parent_taxes'] ?? true" />
                </ClientOnly>
              </template>
            </div>
          </div>
        
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Country Group</label>
              <ClientOnly>
                <SelectBox v-model="form.countryGroupId" :options="getOptions?.['country_groups']?.records || [{id: form.countryGroupId, Name: form.countryGroup}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_countrygroup', 'country_groups')" :loading="loading?.['country_groups'] ?? true" />
              </ClientOnly>

              <label class="label d-block mt-2">Country</label>
              <ClientOnly>
                <SelectBox v-model="form.countryId" :options="getOptions?.['countries']?.records || [{id: form.countryId, Name: form.country}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_country', 'countries')" @change="(val, opt) => setOptions('settings/regions/countries/'+opt.id, 'regions')" :loading="loading?.['countries'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">Region</label>
              <ClientOnly>
                <SelectBox v-model="form.regionId" :options="getOptions?.['regions']?.records || [{id: form.regionId, Name: form.region}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions((form.countryId ? 'settings/regions/countries/'+form.countryId : 'models/c_region'), 'regions')" :loading="loading?.['regions'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">To</label>
              <ClientOnly>
                <SelectBox v-model="form.toCountryGroupId" :options="getOptions?.['to_country_groups']?.records || [{id: form.toCountryGroupId, Name: form.toCountryGroup}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_countrygroup', 'to_country_groups')" :loading="loading?.['to_country_groups'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">To</label>
              <ClientOnly>
                <SelectBox v-model="form.toCountryId" :options="getOptions?.['to_countries']?.records || [{id: form.toCountryId, Name: form.toCountry}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_country', 'to_countries')" @change="(val, opt) => setOptions('settings/regions/countries/'+opt.id, 'to_regions')" :loading="loading?.['to_countries'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">To</label>
              <ClientOnly>
                <SelectBox v-model="form.toRegionId" :options="getOptions?.['to_regions']?.records || [{id: form.toRegionId, Name: form.toRegion}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions((form.toCountryId ? 'settings/regions/countries/'+form.toCountryId : 'models/c_region'), 'to_regions')" :loading="loading?.['to_regions'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <label class="label d-block mt-2">Description</label>
          <textarea v-model="form.description" 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 class="check">
              <input type="checkbox" v-model="form.isDefault" class="checkInput" id="isDefault" :checked="form.isDefault">
              <label class="checkLabel" for="isDefault">Default</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isDocumentLevel" class="checkInput" id="isDocumentLevel" :checked="form.isDocumentLevel">
              <label class="checkLabel" for="isDocumentLevel">Document Level</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isSummary" class="checkInput" id="isSummary" :checked="form.isSummary">
              <label class="checkLabel" for="isSummary">Summary</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isTaxExempt" class="checkInput" id="isTaxExempt" :checked="form.isTaxExempt">
              <label class="checkLabel" for="isTaxExempt">Tax Exempt</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isSalesTax" class="checkInput" id="isSalesTax" :checked="form.isSalesTax">
              <label class="checkLabel" for="isSalesTax">Sales Tax</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.requiresTaxCertificate" class="checkInput" id="requiresTaxCertificate" :checked="form.requiresTaxCertificate">
              <label class="checkLabel" for="requiresTaxCertificate">Requires Tax Certificate</label>
            </div>
          </div>
        </div>
      </div>

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