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

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

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

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 tab = ref(props.modelValue || 'update_notification')
const entries = ref({
  update_notification: []
})
const tabs = ref([
  {value: 'update_notification', text: 'Update Notification'}
])

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

const loadEntries = () => {
  if(props?.entries) {
    entries.value = props.entries
  }
}
onMounted(loadEntries)
watch(() => props.entries, loadEntries)

const addEntry = () => {
  if(tab.value === 'update_notification') {
    entries.value.update_notification.push({
      id: '',
      user: '',
      userId: '',
      isActive: true,
      isSelfService: false
    })
  }

  emit('handler', tab.value, entries.value)
}
const mutateEntry = () => {
  emit('handler', tab.value, entries.value)
}
const destroyEntry = async (entry, index) => {
  entries.value[tab.value].splice(index, 1)

  if(entry.id) {
    await $fetch('/api/requests/request-types/'+entry.id+'/'+tab.value.replaceAll('_', '-'), {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
  emit('handler', tab.value, entries.value)
}

const openTab = async (val) => {
  if(tab.value !== val) {
    tab.value = val
    emit('update:modelValue', tab.value)
    emit('handler', tab.value, entries.value)
    sessionStorage.setItem('request_type_updates_detail_record', tab.value)
  }
}
onMounted(() => {
  const getSessionStorageTab = sessionStorage.getItem('request_type_updates_detail_record')
  if(getSessionStorageTab) {
    openTab(getSessionStorageTab)
  }
})
</script>

<template>
  <div class="card sd-none bd-1px_solid_hexe4e3e6">
    <DetailRecordTab v-model="tab" :tabs="tabs" @handler="(val) => openTab(val.value)" />
    <div class="cardBody p-0px">
      <div class="tableResponsive">
        <table class="table tableList tableFlush" @mouseout="mutateEntry">
          <thead>
            <tr v-if="tab === 'update_notification'">
              <th>User *</th>
              <th class="w-100px">Active</th>
              <th class="w-200px">Self Service</th>
              <th v-if="action !== 'view'" class="w-100px">Action</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="Number(entries[tab]?.length || 0) === 0">
              <td :colspan="action !== 'view' ? 6 : 5" class="align-center">No detail record yet, please add a new one.</td>
            </tr>
            <template v-if="tab === 'update_notification'">
              <tr v-for="(entry, index) in entries[tab]" :key="index">
                <td>
                  <div v-if="action !== 'add' && entry.id !== ''">{{ entry.user }}</div>
                  <div v-else>
                    <ClientOnly>
                      <SelectBox v-model="entry.userId" :options="getOptions?.['users']?.records || entries[tab].map(i => ({id: i.userId, Name: i.user}))" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'users')" :loading="loading?.['users'] ?? true" />
                    </ClientOnly>
                  </div>
                </td>
                <td>
                  <div class="check">
                    <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+tab+'_'+index" :checked="entry.isActive" :disabled="action === 'view'">
                    <label class="checkLabel" :for="'isActive_'+tab+'_'+index">Active</label>
                  </div>
                </td>
                <td>
                  <div class="check">
                    <input type="checkbox" v-model="entry.isSelfService" class="checkInput" :id="'isSelfService_'+tab+'_'+index" :checked="entry.isSelfService" :disabled="action === 'view'">
                    <label class="checkLabel" :for="'isSelfService_'+tab+'_'+index">Self Service</label>
                  </div>
                </td>
                <td v-if="action !== 'view'">
                  <div class="d-flex justify-flexEnd gap-5px">
                    <span @click="destroyEntry(entry, index)" class="cursor-pointer fg-danger">
                      <i class="menu-icon tf-icons ti ti-trash"></i>
                    </span>
                  </div>
                </td>
              </tr>
            </template>
            <tr v-if="action !== 'view'">
              <td colspan="5">
                <button type="button" @click="addEntry" class="button">Add Record</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>