<script setup lang="ts">
import { MaterialSchema, type MaterialFormData } from '~/schemas/material'
import { usePaginatedList } from '~/composables/usePaginatedList'
import { ActionEvents, type HeaderPrep } from '~/components/pub/custom-ui/data/types'
import Dialog from '~/components/pub/base/modal/dialog.vue'
import Header from '~/components/pub/custom-ui/nav-header/prep.vue'
import AppEquipmentEntryForm from '~/components/app/equipment/entry-form.vue'
import RecordConfirmation from '~/components/pub/custom-ui/confirmation/record-confirmation.vue'

// Types
import type { Uom } from '~/models/uom'

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

// Services
import { getSourceMaterials, getSourceMaterialDetail } from '~/services/material.service'
import { getSourceUoms } from '~/services/uom.service'

const uoms = ref<{ value: string; label: string }[]>([])

const getEquipmentDetail = async (id: number | string) => {
  const result = await getSourceMaterialDetail(id)
  if (result.success) {
    recItem.value = result.data
    isFormEntryDialogOpen.value = true
  }
}

const getUomList = async () => {
  const result = await getSourceUoms()
  if (result.success) {
    uoms.value = result.data.map((uom: Uom) => ({ value: uom.code || uom.erp_id, label: uom.name }))
  }
}

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getEquipmentList,
} = usePaginatedList({
  fetchFn: async ({ page }) => {
    const result = await getSourceMaterials({ page })
    return result.data || []
  },
  entityName: 'equipment',
})

const headerPrep: HeaderPrep = {
  title: 'Perlengkapan (BMHP)',
  icon: 'i-lucide-layout-dashboard',
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (_val: string) => {
      // Handle search input - this will be triggered by the header component
    },
    onClick: () => {
      // Handle search button click if needed
    },
    onClear: () => {
      // Handle search clear
    },
  },
  addNav: {
    label: 'Tambah Perlengkapan',
    icon: 'i-lucide-plus',
    onClick: () => {
      isFormEntryDialogOpen.value = true
    },
  },
}

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

// Watch for row actions
watch(recId, () => {
  switch (recAction.value) {
    case ActionEvents.showEdit:
      getEquipmentDetail(recId.value)
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})

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

<template>
  <div class="p-4">
    <Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
    <div class="rounded-md border p-4">
      <AppEquipmentList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />
    </div>

    <Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Perlengkapan" size="lg" prevent-outside>
      <AppEquipmentEntryForm
        :schema="MaterialSchema"
        :uoms="uoms"
        :is-loading="isProcessing"
        @submit="(values: MaterialFormData, resetForm: any) => handleActionSave(values, getEquipmentList, resetForm)"
        @cancel="handleCancelForm"
      />
    </Dialog>

    <!-- Record Confirmation Modal -->
    <RecordConfirmation
      v-model:open="isRecordConfirmationOpen"
      action="delete"
      :record="recItem"
      @confirm="() => handleActionRemove(recId, getEquipmentList)"
      @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>
  </div>
</template>
