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

const route = useRoute()
const organizationId = useCookie('logship_organization_id')

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

const entries = ref([])
const form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  productCategory: props.info?.name || '',
  productCategoryId: props.info?.id || '',
  isActive: true,
  name: '',
  value: '',
  description: '',
  isSummary: false,
  discontinued: false,
  isWebStoreFeatured: false,
  productType: '',
  productTypeId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

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 || organizationId.value || ''
  form.value.productCategory = props.info?.name || ''
  form.value.productCategoryId = props.info?.id || ''
})

const showDetailRecordModal = ref(false)
const showAddressModal = ref(false)
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    productCategory: props.info?.name || '',
    productCategoryId: props.info?.id || '',
    isActive: true,
    name: '',
    value: '',
    description: '',
    isSummary: false,
    discontinued: false,
    isWebStoreFeatured: false,
    productType: '',
    productTypeId: '',
    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(route.params?.id) {
    const res = await $fetch('/api/materials/product-categories/'+route.params.id+'/assigned-products', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || item?.uid || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          productCategory: item?.M_Product_Category_ID?.identifier || '',
          productCategoryId: item?.M_Product_Category_ID?.id || '',
          isActive: item?.IsActive ?? true,
          name: item?.Name || '',
          value: item?.Value || '',
          description: item?.Description || '',
          isSummary: item?.IsSummary ?? false,
          discontinued: item?.Discontinued ?? false,
          isWebStoreFeatured: item?.IsWebStoreFeatured ?? false,
          productType: item?.ProductType?.identifier || '',
          productTypeId: item?.ProductType?.id || '',
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  if(entry.id && confirm('Are you sure want to remove the category from this product')) {
    const res = await $fetch('/api/materials/product-categories/'+entry.id+'/assigned-products', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: entry.id,
        productCategoryId: entry.productCategoryId
      }
    })
    if(res) {
      retrieve()
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Name</th>
            <th>Search Key</th>
            <th>Product Type</th>
            <th>Description</th>
            <th class="w-100px">Active</th>
            <th v-if="action !== 'view'" class="w-100px">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 6 : 5" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.name }}</td>
            <td>{{ entry.value }}</td>
            <td>{{ entry.productType }}</td>
            <td>{{ entry.description }}</td>
            <td class="textAlignCenter">
              <div class="check">
                <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" disabled>
                <!--<label class="checkLabel" :for="'isActive_'+index">Active</label>-->
              </div>
            </td>
            <td v-if="action !== 'view'">
              <div class="d-flex justify-flexEnd gap-5px">
                <span @click="form = entry; showDetailRecordModal = true;" class="cursor-pointer fg-warning">
                  <i class="menu-icon tf-icons ti ti-eye"></i>
                </span>
                <span @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                  <i class="menu-icon tf-icons ti ti-trash"></i>
                </span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <div class="modal" :class="{'active': showDetailRecordModal}" :style="{display: showDetailRecordModal ? 'block' : 'none'}">
      <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeDetailRecordModal">
        <div class="modalContent">
          <div class="modalHeader">
            <h3 class="modalTitle">Assigned Products</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <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-two-thirds">
                  <label class="label d-block">Name *</label>
                  <input type="text" :value="form.name" class="input" readonly />

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Search Key</label>
                      <input type="text" :value="form.value" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Product Type *</label>
                      <input type="text" :value="form.productType" class="input" readonly />
                    </div>
                  </div>

                  <label class="label d-block mt-2">Description</label>
                  <textarea v-model="form.description" class="input" readonly></textarea>
                </div>
                <div class="column is-one-third">
                  <label class="label d-block">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" disabled>
                      <label class="checkLabel" for="isActive">Active</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isSummary" class="checkInput" id="isSummary" :checked="form.isSummary" disabled>
                      <label class="checkLabel" for="isSummary">Summary Level</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.discontinued" class="checkInput" id="discontinued" :checked="form.discontinued" disabled>
                      <label class="checkLabel" for="discontinued">Discontinued</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isWebStoreFeatured" class="checkInput" id="isWebStoreFeatured" :checked="form.isWebStoreFeatured" disabled>
                      <label class="checkLabel" for="isWebStoreFeatured">Featured in Web Store</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modalFooter">
            <div></div>
            <div class="d-flex gap-10px">
              <button type="button" class="button" @click="closeDetailRecordModal">Close</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>