<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')

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 || '',
  tableNumber: props.modelValue.tableNumber ?? '',
  shippingPrinter: props.modelValue.shippingPrinter || '',
  a4Printer: props.modelValue.a4Printer || '',
  synologyCameraId: props.modelValue.synologyCameraId ?? '',
  synologyCamera2Id: props.modelValue.synologyCamera2Id ?? '',
  description: props.modelValue.description || '',
  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
}

// Live camera list from Surveillance Station — lets the user pick by name
// instead of hunting for the numeric id. Loaded lazily (one NAS round-trip)
// when the user opens the dropdown / clicks "Load".
const cameras = ref([])
const camerasLoading = ref(false)
const camerasError = ref('')
const camerasLoaded = ref(false)
const loadCameras = async () => {
  if (camerasLoading.value) return
  camerasLoading.value = true
  camerasError.value = ''
  try {
    const res = await $fetch('/api/surveillance/cameras', {
      headers: useRequestHeaders(['cookie'])
    })
    cameras.value = res?.cameras || []
    camerasLoaded.value = true
    if (!cameras.value.length) camerasError.value = 'No cameras returned by Synology.'
  } catch (e) {
    camerasError.value = 'Could not reach Synology to list cameras — enter the ID manually.'
  } finally {
    camerasLoading.value = 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" />
            </div>
            <div class="column is-half">
              <label class="label d-block">Table Number</label>
              <input type="number" min="1" step="1" v-model="form.tableNumber" class="input" placeholder="e.g. 1" />
              <p class="help">The Tisch number (1, 2, 3, …) — shown on the commissioning page.</p>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Shipping Printer</label>
              <input type="text" v-model="form.shippingPrinter" class="input" placeholder="e.g. labelprinter-1" />
              <p class="help">Label printer key selected on the commissioning page for this table.</p>
            </div>
            <div class="column is-half">
              <label class="label d-block">A4 Printer</label>
              <input type="text" v-model="form.a4Printer" class="input" placeholder="e.g. commission-a4-1" />
              <p class="help">A4/Letter printer for CN23 customs docs (optional).</p>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Synology Camera</label>
              <div class="d-flex gap-10px items-center">
                <div class="select" :class="{ 'is-loading': camerasLoading }" style="flex:1">
                  <select v-model="form.synologyCameraId" @focus="!camerasLoaded && loadCameras()" style="width:100%">
                    <option value="">— select camera —</option>
                    <option v-for="cam in cameras" :key="cam.id" :value="cam.id">{{ cam.id }} — {{ cam.name }}</option>
                    <option v-if="form.synologyCameraId && !cameras.some(c => String(c.id) === String(form.synologyCameraId))" :value="form.synologyCameraId">{{ form.synologyCameraId }} (current)</option>
                  </select>
                </div>
                <input type="number" min="0" step="1" v-model="form.synologyCameraId" class="input" placeholder="ID" style="max-width:90px" />
                <button type="button" class="button" :disabled="camerasLoading" @click="loadCameras">{{ camerasLoading ? '…' : 'Load' }}</button>
              </div>
              <p class="help">
                Camera that films this table — pick from the list or enter its ID.
                <span v-if="camerasError" class="has-text-danger">{{ camerasError }}</span>
              </p>
            </div>
            <div class="column is-half">
              <label class="label d-block">Synology Camera 2 <span class="has-text-grey">(optional)</span></label>
              <div class="d-flex gap-10px items-center">
                <div class="select" :class="{ 'is-loading': camerasLoading }" style="flex:1">
                  <select v-model="form.synologyCamera2Id" @focus="!camerasLoaded && loadCameras()" style="width:100%">
                    <option value="">— none —</option>
                    <option v-for="cam in cameras" :key="cam.id" :value="cam.id">{{ cam.id }} — {{ cam.name }}</option>
                    <option v-if="form.synologyCamera2Id && !cameras.some(c => String(c.id) === String(form.synologyCamera2Id))" :value="form.synologyCamera2Id">{{ form.synologyCamera2Id }} (current)</option>
                  </select>
                </div>
                <input type="number" min="0" step="1" v-model="form.synologyCamera2Id" class="input" placeholder="ID" style="max-width:90px" />
                <button type="button" class="button" :disabled="camerasLoading" @click="loadCameras">{{ camerasLoading ? '…' : 'Load' }}</button>
              </div>
              <p class="help">Second camera for this table (if any). Both videos are shown together.</p>
            </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}" :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>
