<script setup lang="ts">
// Components
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import AppItemList from '~/components/app/item/list.vue'
import AppItemEntryForm from '~/components/app/item/entry-form.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'

// Constants
import { itemGroupCodes } from '~/lib/constants'

// Helpers
import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'

// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'
import { ItemSchema, type ItemFormData } from '~/schemas/item.schema'

// Handlers
import {
  recId,
  recAction,
  recItem,
  isReadonly,
  isProcessing,
  isFormEntryDialogOpen,
  isRecordConfirmationOpen,
  onResetState,
  handleActionSave,
  handleActionEdit,
  handleActionRemove,
  handleCancelForm,
} from '~/handlers/item.handler'

// Services
import { getList, getDetail } from '~/services/item.service'
import { getValueLabelList as getUomList } from '~/services/uom.service'

const itemGroups = ref<{ value: string | number; label: string }[]>([])
const uoms = ref<{ value: string | number; label: string }[]>([])
const title = ref('')

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getItemList,
} = usePaginatedList({
  fetchFn: async (params: any) => {
    const result = await getList({
      search: params.search,
      sort: 'createdAt:asc',
      'page-number': params['page-number'] || 0,
      'page-size': params['page-size'] || 10,
      includes: 'uom',
    })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'item',
})

const headerPrep: HeaderPrep = {
  title: 'Item',
  icon: 'i-lucide-layout-list',
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (val: string) => {
      searchInput.value = val
    },
    onClick: () => {},
    onClear: () => {},
  },
  addNav: {
    label: 'Tambah',
    icon: 'i-lucide-plus',
    onClick: () => {
      recItem.value = null
      recId.value = 0
      isFormEntryDialogOpen.value = true
      isReadonly.value = false
    },
  },
}

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)

const getCurrentDetail = async (id: number | string) => {
  const result = await getDetail(id)
  if (result.success) {
    const currentValue = result.body?.data || {}
    recItem.value = currentValue
    isFormEntryDialogOpen.value = true
  }
}

watch([recId, recAction], () => {
  const currentId = recItem.value?.code ? recItem.value.code : recId.value
  switch (recAction.value) {
    case ActionEvents.showDetail:
      getCurrentDetail(currentId)
      title.value = 'Detail Item'
      isReadonly.value = true
      break
    case ActionEvents.showEdit:
      getCurrentDetail(currentId)
      title.value = 'Edit Item'
      isReadonly.value = false
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})

onMounted(async () => {
  itemGroups.value = Object.keys(itemGroupCodes).map((key) => ({
    value: key,
    label: itemGroupCodes[key],
  })) as any
  uoms.value = await getUomList()
  await getItemList()
})
</script>

<template>
  <Header
    v-model="searchInput"
    :prep="headerPrep"
    :ref-search-nav="headerPrep.refSearchNav"
    @search="handleSearch"
  />

  <AppItemList
    :data="data"
    :pagination-meta="paginationMeta"
    @page-change="handlePageChange"
  />

  <Dialog
    v-model:open="isFormEntryDialogOpen"
    :title="!!recItem ? title : 'Tambah Item'"
    size="lg"
    prevent-outside
    @update:open="
      (value: any) => {
        onResetState()
        isFormEntryDialogOpen = value
      }
    "
  >
    <AppItemEntryForm
      :schema="ItemSchema"
      :values="recItem"
      :item-groups="itemGroups"
      :uoms="uoms"
      :is-loading="isProcessing"
      :is-readonly="isReadonly"
      @submit="
        (values: ItemFormData | Record<string, any>, resetForm: () => void) => {
          if (recId > 0) {
            handleActionEdit(recItem?.code ? recItem.code : recId, values, getItemList, resetForm, toast)
            return
          }
          handleActionSave(values, getItemList, resetForm, toast)
        }
      "
      @cancel="handleCancelForm"
    />
  </Dialog>

  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="() => handleActionRemove(recItem?.code ? recItem.code : recId, getItemList, toast)"
    @cancel=""
  >
    <template #default="{ record }">
      <div class="text-sm">
        <p>
          <strong>ID:</strong>
          {{ record?.id }}
        </p>
        <p v-if="record?.name">
          <strong>Nama:</strong>
          {{ record.name }}
        </p>
        <p v-if="record?.code">
          <strong>Kode:</strong>
          {{ record.code }}
        </p>
      </div>
    </template>
  </RecordConfirmation>
</template>
