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

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 || '',
  dateFrom: props.modelValue.dateFrom || date.now('date'),
  dateTo: props.modelValue.dateTo || '',
  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
}

// A single non-working day = only DateFrom. A range = DateFrom + DateTo.
const isRange = computed({
  get: () => !!form.value.dateTo,
  set: (val) => {
    // When switching to a range, seed DateTo with DateFrom so the picker opens
    // on a sensible day; when switching back to a single day, clear it.
    form.value.dateTo = val ? (form.value.dateTo || form.value.dateFrom) : ''
  }
})

// DateTo must not be before DateFrom.
const dateRangeInvalid = computed(() =>
  !!form.value.dateTo && !!form.value.dateFrom && form.value.dateTo < form.value.dateFrom
)

const invalid = computed(() =>
  form.value.name.trim() === '' || !form.value.dateFrom || dateRangeInvalid.value || form.value.processing
)

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

const save = (saveType = '') => {
  if(invalid.value) return
  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. Fronleichnam" />
              <p class="help">Shown to customers on the dashboard when they hover the marked day.</p>
            </div>
            <div class="column is-half">
              <label class="label d-block">Type</label>
              <div class="d-flex flexDirection-column">
                <div class="check">
                  <input type="checkbox" v-model="isRange" class="checkInput" id="isRange">
                  <label class="checkLabel" for="isRange">Date range (multiple days)</label>
                </div>
              </div>
              <p class="help">Leave unchecked for a single non-working day.</p>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">{{ isRange ? 'Date From *' : 'Date *' }}</label>
              <DatePicker v-model="form.dateFrom" />
            </div>
            <div class="column is-half">
              <template v-if="isRange">
                <label class="label d-block">Date To *</label>
                <DatePicker v-model="form.dateTo" />
                <p v-if="dateRangeInvalid" class="help has-text-danger">Date To must be on or after Date From.</p>
              </template>
            </div>
          </div>

          <label class="label d-block mt-2">Description</label>
          <textarea v-model="form.description" class="input" placeholder="e.g. Feiertag"></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" />
          <p class="help">Choose the shared org <strong>*</strong> to apply the closure to every customer.</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">
            <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="invalid ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
        <button type="button" @click="save('preview')" class="button" :class="invalid ? 'pointerEvents-none opacity-0.6' : ''">Submit &amp; Preview</button>
        <button type="button" @click="save('changes')" class="button" :class="invalid ? 'pointerEvents-none opacity-0.6' : ''">Save Changes</button>
      </div>
    </div>
  </form>
</template>
