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

const props = defineProps({
  modelValue: Object,
  tab: String
})

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 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 form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue.uid || '',
  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 || '',
  requestEMail: props.modelValue.requestEMail || '',
  requestFolder: props.modelValue.requestFolder || '',
  requestUser: props.modelValue.requestUser || '',
  isMultiLingualDocument: props.modelValue.isMultiLingualDocument ?? false,
  isSmtpAuthorization: props.modelValue.isSmtpAuthorization ?? false,
  isUseBetaFunctions: props.modelValue.isUseBetaFunctions ?? false,
  isPostImmediate: props.modelValue.isPostImmediate ?? false,
  isUseASP: props.modelValue.isUseASP ?? false,
  isSecureSMTP: props.modelValue.isSecureSMTP ?? false,
  language: props.modelValue.language || '',
  languageId: props.modelValue.languageId || 'en_US',
  autoArchive: props.modelValue.autoArchive || '',
  autoArchiveId: props.modelValue.autoArchiveId || 'N',
  mMPolicy: props.modelValue.mMPolicy || '',
  mMPolicyId: props.modelValue.mMPolicyId || 'F',
  authenticationType: props.modelValue.authenticationType || '',
  authenticationTypeId: props.modelValue.authenticationTypeId || '',
  fulfillmentProduct: props.modelValue.fulfillmentProduct || '',
  fulfillmentProductId: props.modelValue.fulfillmentProductId || '',
  fulfillmentReturnProduct: props.modelValue.fulfillmentReturnProduct || '',
  fulfillmentReturnProductId: props.modelValue.fulfillmentReturnProductId || '',
  rentWarehouseQm3Product: props.modelValue.rentWarehouseQm3Product || '',
  rentWarehouseQm3ProductId: props.modelValue.rentWarehouseQm3ProductId || '',
  shelfSmallProduct: props.modelValue.shelfSmallProduct || '',
  shelfSmallProductId: props.modelValue.shelfSmallProductId || '',
  shelfLargeProduct: props.modelValue.shelfLargeProduct || '',
  shelfLargeProductId: props.modelValue.shelfLargeProductId || '',
  palettSpaceProduct: props.modelValue.palettSpaceProduct || '',
  palettSpaceProductId: props.modelValue.palettSpaceProductId || '',
  paket1KPProduct: props.modelValue.paket1KPProduct || '',
  paket1KPProductId: props.modelValue.paket1KPProductId || '',
  paket1KPPrice: props.modelValue.paket1KPPrice || 0,
  paket2SProduct: props.modelValue.paket2SProduct || '',
  paket2SProductId: props.modelValue.paket2SProductId || '',
  paket2SPrice: props.modelValue.paket2SPrice || 0,
  paket3MProduct: props.modelValue.paket3MProduct || '',
  paket3MProductId: props.modelValue.paket3MProductId || '',
  paket3MPrice: props.modelValue.paket3MPrice || 0,
  paket4LProduct: props.modelValue.paket4LProduct || '',
  paket4LProductId: props.modelValue.paket4LProductId || '',
  paket4LPrice: props.modelValue.paket4LPrice || 0,
  paket5XLProduct: props.modelValue.paket5XLProduct || '',
  paket5XLProductId: props.modelValue.paket5XLProductId || '',
  paket5XLPrice: props.modelValue.paket5XLPrice || 0,
  logShipFeeProduct: props.modelValue.logShipFeeProduct || '',
  logShipFeeProductId: props.modelValue.logShipFeeProductId || '',
  logShipFeePrice: props.modelValue.logShipFeePrice || 0,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false,
  }
})

watch(() => props.modelValue, (newValue) => {
  // Only update form if the value has actually changed from the parent
  // This prevents overwriting user changes that are in the process of being saved
  if (newValue && newValue !== form.value) {
    form.value = { ...newValue }
  }
}, { deep: false })

// Watch for all price fields changes
watch(() => [
  form.value.paket1KPPrice,
  form.value.paket2SPrice,
  form.value.paket3MPrice,
  form.value.paket4LPrice,
  form.value.paket5XLPrice,
  form.value.logShipFeePrice
], (newValues, oldValues) => {
  if (JSON.stringify(newValues) !== JSON.stringify(oldValues)) {
    console.log('Price field changed:', { newValues, oldValues })
    save()
  }
})

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="save">
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <template v-if="tab === 'basic'">
        <!-- Basic Information Card -->
        <div class="card mb-4" style="border: 2px solid #dbdbdb; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div class="card-header" style="background-color: #f5f5f5; border-bottom: 2px solid #dbdbdb;">
            <h3 class="card-header-title" style="font-weight: 600;">Basic Information</h3>
          </div>
          <div class="card-content">
            <div class="columns is-desktop">
              <div class="column is-one-third">
                <label class="label d-block">Name *</label>
                <input type="text" v-model="form.name" class="input" @keyup="save" />
              </div>
              <div class="column is-one-third">
                <label class="label d-block">Language</label>
                <ClientOnly>
                  <SelectBox v-model="form.languageId" :options="getOptions?.['languages']?.records || [{id: 'en_US', Name: 'English (US)'}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_language', 'languages')" :loading="loading?.['languages'] ?? true" @change="save" />
                </ClientOnly>
              </div>
              <div class="column is-one-third">
                <label class="label d-block">Status</label>
                <div class="d-flex flexDirection-column gap-5px">
                  <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.isUseBetaFunctions" class="checkInput" id="isUseBetaFunctions" :checked="form.isUseBetaFunctions" @change="save">
                    <label class="checkLabel" for="isUseBetaFunctions">Use Beta Functions</label>
                  </div>
                  <div class="check">
                    <input type="checkbox" v-model="form.isMultiLingualDocument" class="checkInput" id="isMultiLingualDocument" :checked="form.isMultiLingualDocument" @change="save">
                    <label class="checkLabel" for="isMultiLingualDocument">Multi Lingual Documents</label>
                  </div>
                </div>
              </div>
            </div>
            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Description</label>
                <textarea v-model="form.description" class="input" @keyup="save"></textarea>
              </div>
              <div class="column is-one-quarter">
                <label class="label d-block">Auto Archive</label>
                <select v-model="form.autoArchiveId" class="select" @change="save">
                  <option value="N">None</option>
                </select>
              </div>
              <div class="column is-one-quarter">
                <label class="label d-block">Material Policy</label>
                <select v-model="form.mMPolicyId" class="select" @change="save">
                  <option value="F">FiFo</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        <!-- Request Management Card -->
        <div class="card mb-4" style="border: 2px solid #dbdbdb; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div class="card-header" style="background-color: #f5f5f5; border-bottom: 2px solid #dbdbdb;">
            <h3 class="card-header-title" style="font-weight: 600;">Request Management</h3>
          </div>
          <div class="card-content">
            <div class="columns is-desktop">
              <div class="column is-one-third">
                <label class="label d-block">Request EMail</label>
                <input type="text" v-model="form.requestEMail" class="input" @keyup="save" />
              </div>
              <div class="column is-one-third">
                <label class="label d-block">Request Folder</label>
                <input type="text" v-model="form.requestFolder" class="input" @keyup="save" />
              </div>
              <div class="column is-one-third">
                <label class="label d-block">Request User</label>
                <input type="text" v-model="form.requestUser" class="input" @keyup="save" />
              </div>
            </div>
            <div class="columns is-desktop">
              <div class="column">
                <label class="label d-block">SMTP Settings</label>
                <div class="d-flex gap-20px">
                  <div class="check">
                    <input type="checkbox" v-model="form.isSmtpAuthorization" class="checkInput" id="isSmtpAuthorization" :checked="form.isSmtpAuthorization" @change="save">
                    <label class="checkLabel" for="isSmtpAuthorization">SMTP Authentication</label>
                  </div>
                  <div class="check">
                    <input type="checkbox" v-model="form.isSecureSMTP" class="checkInput" id="isSecureSMTP" :checked="form.isSecureSMTP" @change="save">
                    <label class="checkLabel" for="isSecureSMTP">SMTP SSL/TLS</label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Fulfillment Products Card -->
        <div class="card mb-4" style="border: 2px solid #dbdbdb; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div class="card-header" style="background-color: #f5f5f5; border-bottom: 2px solid #dbdbdb;">
            <h3 class="card-header-title" style="font-weight: 600;">Fulfillment Products</h3>
          </div>
          <div class="card-content">
            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Fulfillment Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.fulfillmentProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
              </div>
              <div class="column is-half">
                <label class="label d-block">Fulfillment Return Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.fulfillmentReturnProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
              </div>
            </div>
          </div>
        </div>

        <!-- Warehouse Rental Products Card -->
        <div class="card mb-4" style="border: 2px solid #dbdbdb; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div class="card-header" style="background-color: #f5f5f5; border-bottom: 2px solid #dbdbdb;">
            <h3 class="card-header-title" style="font-weight: 600;">Warehouse Rental Products</h3>
          </div>
          <div class="card-content">
            <div class="columns is-desktop">
              <div class="column is-one-third">
                <label class="label d-block">Rent Warehouse Qm3 Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.rentWarehouseQm3ProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
              </div>
              <div class="column is-one-third">
                <label class="label d-block">Shelf Small Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.shelfSmallProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
              </div>
              <div class="column is-one-third">
                <label class="label d-block">Shelf Large Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.shelfLargeProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
              </div>
            </div>
            <div class="columns is-desktop">
              <div class="column is-one-third">
                <label class="label d-block">Palett Space Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.palettSpaceProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
              </div>
            </div>
          </div>
        </div>

        <!-- Package Products & Pricing Card -->
        <div class="card mb-4" style="border: 2px solid #dbdbdb; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div class="card-header" style="background-color: #f5f5f5; border-bottom: 2px solid #dbdbdb;">
            <h3 class="card-header-title" style="font-weight: 600;">Package Products & Pricing</h3>
          </div>
          <div class="card-content">
            <div class="columns is-desktop">
              <div class="column is-one-fifth">
                <label class="label d-block">Paket 1 KP Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.paket1KPProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
                <label class="label d-block mt-1">Price</label>
                <input type="number" step="0.01" v-model="form.paket1KPPrice" class="input" @keyup="save" />
              </div>
              <div class="column is-one-fifth">
                <label class="label d-block">Paket 2 S Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.paket2SProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
                <label class="label d-block mt-1">Price</label>
                <input type="number" step="0.01" v-model="form.paket2SPrice" class="input" @keyup="save" />
              </div>
              <div class="column is-one-fifth">
                <label class="label d-block">Paket 3 M Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.paket3MProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
                <label class="label d-block mt-1">Price</label>
                <input type="number" step="0.01" v-model="form.paket3MPrice" class="input" @keyup="save" />
              </div>
              <div class="column is-one-fifth">
                <label class="label d-block">Paket 4 L Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.paket4LProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
                <label class="label d-block mt-1">Price</label>
                <input type="number" step="0.01" v-model="form.paket4LPrice" class="input" @keyup="save" />
              </div>
              <div class="column is-one-fifth">
                <label class="label d-block">Paket 5 XL Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.paket5XLProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
                <label class="label d-block mt-1">Price</label>
                <input type="number" step="0.01" v-model="form.paket5XLPrice" class="input" @keyup="save" />
              </div>
            </div>
          </div>
        </div>

        <!-- LogShip Fee Card -->
        <div class="card mb-4" style="border: 2px solid #dbdbdb; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <div class="card-header" style="background-color: #f5f5f5; border-bottom: 2px solid #dbdbdb;">
            <h3 class="card-header-title" style="font-weight: 600;">LogShip Fee</h3>
          </div>
          <div class="card-content">
            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">LogShip Fee Product</label>
                <ClientOnly>
                  <SelectBox v-model="form.logShipFeeProductId" :options="getOptions?.['products']?.records || []" prop="Name" dataprop="id" datatype="number" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" @change="save" />
                </ClientOnly>
              </div>
              <div class="column is-half">
                <label class="label d-block">LogShip Fee Price</label>
                <input type="number" step="0.01" v-model="form.logShipFeePrice" class="input" @keyup="save" />
              </div>
            </div>
          </div>
        </div>
      </template>

    </div>
  </div>
</template>