<script setup>
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 { data: countries } = await useFetch('/api/settings/countries', {
  headers: useRequestHeaders(['cookie'])
})

const { data: regions } = await useFetch('/api/settings/regions', {
  headers: useRequestHeaders(['cookie'])
})

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 || '',
  address1: props.modelValue.address1 || '',
  city: props.modelValue.city || '',
  isActive: props.modelValue.isActive ?? true,
  isValid: props.modelValue.isValid ?? false,
  countryId: props.modelValue.countryId || '',
  regionId: props.modelValue.regionId || '',
  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) {
    /*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 = () => {
  form.value.processing = true
  emit('update:modelValue', form.value)
  if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id)
  } else {
    emit('save', form.value, '')
  }
}
</script>

<template>
  <form @submit.prevent="save">
    <div class="row m-3 mt-0">
      <div v-if="form.alert.status" class="col-md-12 mb-3">
        <div class="alert" :class="Number(form.alert.status) >= 400 ? 'alert-danger' : 'alert-success'">
          <div class="alertContent">
            <h3 class="alertTitle">{{ form.alert.status }}</h3>
            <p class="alertText">{{ form.alert.message }}</p>
          </div>
          <div class="alertAction" @click="form.alert.status = ''"><i class="menu-icon tf-icons ti ti-x"></i></div>
        </div>
      </div>

      <div class="col-md-6 mb-3">
        <label class="label">Tenant *</label>
        <input type="text" :value="clientName" class="input" readonly />
      </div>
      <div class="col-md-6 mb-3">
        <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="col-md-6 mb-3">
        <label class="label">Address *</label>
        <input type="text" v-model="form.address1" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">City</label>
        <input type="text" v-model="form.city" class="input" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Country *</label>
        <SelectBox v-model="form.countryId" :options="countries.records" prop="Name" dataprop="id" datatype="string" :size="5" />
      </div>
      <div class="col-md-6 mb-3">
        <label class="label">Region</label>
        <SelectBox v-model="form.regionId" :options="regions.records" prop="Name" dataprop="id" datatype="string" :size="5" />
      </div>
      <div class="col-md-12 mb-3">
        <label class="label d-block mb-2">Status</label>
        <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.isValid" class="checkInput" id="isValid" :checked="form.isValid">
          <label class="checkLabel" for="isValid">Valid</label>
        </div>
      </div>
    </div>
    <div class="row m-3">
      <div class="col-md-12 mb-3">
        <button type="submit" class="button primary-light" :class="(form.address1 === '' || form.countryId === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
      </div>
    </div>
  </form>
</template>