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

const props = defineProps({
  modelValue: Object
})

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

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

// PrinterType AD_Reference List codes (stored id) ↔ label, per the
// CUST_Printer.PrinterType reference: { id: 'lab' → 'Label', id: 'pap' → 'Paper' }.
const PRINTER_TYPES = [
  { value: 'lab', label: 'Label printer' },
  { value: 'pap', label: 'Paper / A4 printer' }
]

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 || '',
  cupsName: props.modelValue.cupsName || '',
  printerType: props.modelValue.printerType || '',
  defaultPrintOptions: props.modelValue.defaultPrintOptions || '',
  locationDevice: props.modelValue.locationDevice || '',
  seqNo: props.modelValue.seqNo ?? '',
  value: props.modelValue.value || '',
  isDefault: props.modelValue.isDefault ?? false,
  isActive: props.modelValue.isActive ?? true,
  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) {
    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">
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Name *</label>
              <input type="text" v-model="form.name" class="input" placeholder="e.g. Tisch 1 – Versandlabel" />
              <p class="help">Descriptive name shown in printer pickers.</p>
            </div>
            <div class="column is-half">
              <label class="label d-block">CUPS Name *</label>
              <input type="text" v-model="form.cupsName" class="input" placeholder="e.g. labelprinter-1" />
              <p class="help">The exact CUPS queue name passed to <code>lp -d</code>.</p>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Printer Type</label>
              <div class="select is-fullwidth">
                <select v-model="form.printerType" style="width:100%">
                  <option value="">— select type —</option>
                  <option v-for="t in PRINTER_TYPES" :key="t.value" :value="t.value">{{ t.label }}</option>
                </select>
              </div>
              <p class="help">Label printer (small stock) or paper/A4 printer.</p>
            </div>
            <div class="column is-half">
              <label class="label d-block">Default Print Options</label>
              <input type="text" v-model="form.defaultPrintOptions" class="input" placeholder="e.g. -o fit-to-page" />
              <p class="help">CUPS options applied by default when printing to this device.</p>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Location / Device</label>
              <input type="text" v-model="form.locationDevice" class="input" placeholder="e.g. Tisch 1 / office / warehouse corner" />
              <p class="help">Where the printer physically sits.</p>
            </div>
            <div class="column is-half">
              <label class="label d-block">Sequence</label>
              <input type="number" min="0" step="1" v-model="form.seqNo" class="input" placeholder="e.g. 10" />
              <p class="help">Ordering in printer dropdowns (lowest first).</p>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Value <span class="has-text-grey">(optional)</span></label>
              <input type="text" v-model="form.value" class="input" placeholder="auto" />
              <p class="help">Short code — auto-filled by iDempiere if left blank.</p>
            </div>
            <div class="column is-half"></div>
          </div>
        </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}" :loading="loading?.['orgs'] ?? true" />
          <p class="help">Pick <strong>*</strong> (org 0) to share this printer across all organizations.</p>

          <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 gap-10px">
            <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 printer (for its type)</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.cupsName === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
        <button type="button" @click="save('preview')" class="button" :class="(form.name === '' || form.cupsName === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit &amp; Preview</button>
        <button type="button" @click="save('changes')" class="button" :class="(form.name === '' || form.cupsName === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save Changes</button>
      </div>
    </div>
  </form>
</template>
