<script setup>
import { date } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
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 || '',
  description: props.modelValue.description || '',
  value: props.modelValue.value || '',
  startDate: props.modelValue.startDate || date.now('date'),
  endDate: props.modelValue.endDate || date.now('date'),
  costs: props.modelValue.costs || 0,
  isSummary: props.modelValue.isSummary ?? false,
  channel: props.modelValue.channel || '',
  channelId: props.modelValue.channelId || '',
  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) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

watch(() => props.modelValue, () => {
  form.value = props.modelValue
})

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const save = debounce(() => {
  emit('update:modelValue', form.value)
  emit('save', form.value)
})
</script>

<template>
  <div @mouseleave.self="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">
              <div class="legend">
                <label class="label">Name *</label>
                <input type="text" v-model="form.name" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Costs *</label>
                <input type="text" v-model="form.costs" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Start Date</label>
                <DatePicker v-model="form.startDate" @handler="save" />
              </div>
            </div>
            <div class="column is-half">
              <div class="legend">
                <label class="label">Search Key</label>
                <input type="text" v-model="form.value" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Channel</label>
                <ClientOnly>
                  <SelectBox v-model="form.channelId" :options="getOptions?.['channels']?.records || [{id: form.channelId, Name: form.channel}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_channel', 'channels')" @change="save" :loading="loading?.['channels'] ?? true" />
                </ClientOnly>
              </div>
              
              <div class="legend mt-2">
                <label class="label">End Date</label>
                <DatePicker v-model="form.endDate" @handler="save" />
              </div>
            </div>
          </div>

          <div class="legend mt-2">
            <label class="label">Description</label>
            <textarea v-model="form.description" class="input" @keyup="save"></textarea>
          </div>
        </div>
        <div class="column is-one-third">
          <div class="legend">
            <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="legend mt-2">
            <label class="label">Tenant *</label>
            <input type="text" :value="clientName" class="input" readonly />
          </div>

          <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" @change="save">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isSummary" class="checkInput" id="isSummary" :checked="form.isSummary" @change="save">
              <label class="checkLabel" for="isSummary">Summary</label>
            </div>
          </div>
        </div>
      </div>
      
    </div>
  </div>
</template>