<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 RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'

// Helpers
import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'
import { config } from './procedure-list-cfg'

// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'
import { ProcedureSrcSchema, type ProcedureSrcFormData } from '~/schemas/procedure-src.schema'

// Handlers
import {
  isReadonly,
  isProcessing,
  isFormEntryDialogOpen,
  isRecordConfirmationOpen,
  onResetState,
  handleActionSave,
  handleActionEdit,
  handleActionRemove,
  handleCancelForm,
} from '~/handlers/procedure-src.handler'

// Services
import { getList, getDetail } from '~/services/procedure-src.service'

const title = ref('')

interface Props {
  processFn: (input: unknown) => void
}
const props = defineProps<Props>()

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

const headerPrep: HeaderPrep = {
  title: 'MCU Prosedur',
  icon: 'i-lucide-clipboard-list',
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (val: string) => {
      searchInput.value = val
    },
    onClick: () => {},
    onClear: () => {},
  },
}

const recId = ref<string>(``)
const recAction = ref<string>(``)
const recItem = ref<any>({})
provide('ap_rec_id', recId)
provide('ap_rec_action', recAction)
provide('ap_rec_item', recItem)
provide('table_data_loader', isLoading)

const isModalOpen = inject(`isProcedurePickerDialogOpen`) as Ref<boolean>

watch([recId, recAction], () => {
  switch (recAction.value) {
    case ActionEvents.showProcess:
      props.processFn({
        id: recId.value,
        code: recItem.value.code,
        name: recItem.value.name,
      })
      isModalOpen.value = false
      break
  }
})

onMounted(async () => {
  await getItemList()
})
</script>

<template>
  <Dialog
    v-model:open="isModalOpen"
    title=""
    size="xl"
  >
    <Header
      v-model="searchInput"
      :prep="headerPrep"
      :ref-search-nav="headerPrep.refSearchNav"
      @search="handleSearch"
      class=""
    />
    <AppProcedureSrcList
      :table-config="config"
      :data="data"
      :pagination-meta="paginationMeta"
      @page-change="handlePageChange"
    />
  </Dialog>
</template>
