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

const props = defineProps({
  modelValue: Boolean,
  location: String,
  locationId: String,
  info: Object
})

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

const organizationId = useCookie('logship_organization_id')

const form = ref({
  id: props.locationId || '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: organizationId.value || '',
  isActive: true,
  address1: '',
  address2: '',
  address3: '',
  address4: '',
  city: '',
  postal: '',
  regionName: '',
  isValid: true,
  country: '',
  countryId: '',
  region: '',
  regionId: '',
  alert: {
    status: '',
    message: '',
    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
}

const retrieve = async () => {
  if(props.locationId) {
    const res = await $fetch('/api/settings/locations/'+props.locationId, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      form.value = {
        id: res?.id || '',
        client: res?.AD_Client_ID?.identifier || '',
        clientId: res?.AD_Client_ID?.id || '',
        organization: res?.AD_Org_ID?.identifier || '',
        organizationId: res?.AD_Org_ID?.id || '',
        isActive: res?.IsActive ?? true,
        address1: res?.Address1 || '',
        address2: res?.Address2 || '',
        address3: res?.Address3 || '',
        address4: res?.Address4 || '',
        city: res?.City || '',
        postal: res?.Postal || '',
        regionName: res?.RegionName || '',
        isValid: res?.IsValid ?? true,
        country: res?.C_Country_ID?.identifier || '',
        countryId: res?.C_Country_ID?.id || '',
        region: res?.C_Region_ID?.identifier || '',
        regionId: res?.C_Region_ID?.id || '',
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    }
  } else {
    form.value = {
      id: '',
      client: '',
      clientId: '',
      organization: '',
      organizationId: props.info?.organizationId || organizationId.value || '',
      isActive: true,
      address1: '',
      address2: '',
      address3: '',
      address4: '',
      city: '',
      postal: '',
      regionName: '',
      isValid: true,
      country: '',
      countryId: '',
      region: '',
      regionId: '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
  }
}
onMounted(retrieve)

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || ''
})

watch(() => props.locationId, () => {
  form.value.id = props.locationId || ''
  retrieve()
})

const showAddressModal = ref(props.modelValue || false)
const closeAddressModal = () => {
  showAddressModal.value = false
  emit('update:modelValue', false)
}
watch(() => props.modelValue, () => {
  showAddressModal.value = props.modelValue
})

const save = async () => {
  if(form.value.id !== '') {
    const res = await $fetch('/api/settings/locations/update', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        address1: form.value.address1,
        address2: form.value.address2,
        address3: form.value.address3,
        address4: form.value.address4,
        city: form.value.city,
        postal: form.value.postal,
        regionName: form.value.regionName,
        isValid: form.value.isValid,
        countryId: form.value.countryId,
        regionId: form.value.regionId
      }
    })
    if(Number(res.status) === 200) {
      emit('update:locationId', res.id)
      emit('update:location', `${form.value.address1}, ${form.value.address2}, ${form.value.address3}, ${form.value.address4}, ${form.value.postal ? 'D-'+form.value.postal : ''}, ${form.value.city}, ${form.value.region}, ${form.value.country}`)
      closeAddressModal()
    } else {
      form.value.alert.status = res.status
      form.value.alert.message = res.message
      form.value.alert.processing = false
    }
  } else {
    const res = await $fetch('/api/settings/locations/store', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        address1: form.value.address1,
        address2: form.value.address2,
        address3: form.value.address3,
        address4: form.value.address4,
        city: form.value.city,
        postal: form.value.postal,
        regionName: form.value.regionName,
        isValid: form.value.isValid,
        countryId: form.value.countryId,
        regionId: form.value.regionId
      }
    })
    if(Number(res.status) === 200) {
      emit('update:locationId', res.id)
      emit('update:location', `${form.value.address1}, ${form.value.address2}, ${form.value.address3}, ${form.value.address4}, ${form.value.postal ? 'D-'+form.value.postal : ''}, ${form.value.city}, ${form.value.region}, ${form.value.country}`)
      closeAddressModal()
    } else {
      form.value.alert.status = res.status
      form.value.alert.message = res.message
      form.value.alert.processing = false
    }
  }
}
</script>

<template>
  <div class="modal" :class="{'active': showAddressModal}" :style="{display: showAddressModal ? 'block' : 'none'}">
    <div class="modalDialog modalCenter" @click.self="closeAddressModal">
      <div class="modalContent">
        <div class="modalHeader">
          <h3 class="modalTitle">Location</h3>
          <div class="cursor-pointer" @click="closeAddressModal">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>
        <div class="modalBody">
          <div class="my-5 mx-5">
            <AlertAction v-model='form.alert.status' :alert="form.alert" />
            <div class="columns">
              <div class="column is-full">
                <label class="label d-block">Address 1 *</label>
                <input type="text" v-model="form.address1" class="input" />

                <label class="label d-block mt-2">Address 2</label>
                <input type="text" v-model="form.address2" class="input" />

                <label class="label d-block mt-2">Address 3</label>
                <input type="text" v-model="form.address3" class="input" />

                <label class="label d-block mt-2">Address 4</label>
                <input type="text" v-model="form.address4" class="input" />

                <label class="label d-block mt-2">Country *</label>
                <ClientOnly>
                  <SelectBox v-model="form.countryId" :options="getOptions?.['countries']?.records || [{id: form.countryId, Name: form.country}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_country', 'countries')" @change="(val, opt) => {setOptions('settings/regions/countries/'+opt.id, 'regions'); form.country = opt.Name;}" :loading="loading?.['countries'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Region</label>
                <ClientOnly v-if="form.countryId && (Number(getOptions?.['regions']?.records?.length || 0) >= 1 || form.regionId)">
                  <SelectBox v-model="form.regionId" :options="getOptions?.['regions']?.records || [{id: form.regionId, Name: form.region}]" prop="Name" dataprop="id" datatype="string" :size="5" @change="(val, opt) => {form.region = opt.Name; form.regionName = opt.Name;}" :loading="loading?.['regions'] ?? true" />
                </ClientOnly>
                <input v-else type="text" v-model="form.regionName" class="input" />

                <label class="label d-block mt-2">City</label>
                <input type="text" v-model="form.city" class="input" />

                <label class="label d-block mt-2">ZIP</label>
                <input type="text" v-model="form.postal" class="input" />

                <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 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>
          </div>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="closeAddressModal">Close</button>
            <button type="button" class="button" @click="save" :class="(form.address1 === '' || form.countryId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>