<script setup lang="ts">
// Components
import Dialog from '~/components/pub/base/modal/dialog.vue'
import Header from '~/components/pub/custom-ui/nav-header/prep.vue'
import AppToolsEntryForm from '~/components/app/tools/entry-form.vue'
import RecordConfirmation from '~/components/pub/custom-ui/confirmation/record-confirmation.vue'

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

// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/custom-ui/data/types'
import { DeviceSchema, type DeviceFormData } from '~/schemas/device.schema'
import type { Uom } from '~/models/uom'

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

// Services
import { getDevices, getDeviceDetail } from '~/services/device.service'
import { getUoms } from '~/services/uom.service'

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

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getToolsList,
} = usePaginatedList({
  fetchFn: async ({ page }) => {
    const result = await getDevices({ search: searchInput.value, page })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'device',
})

const headerPrep: HeaderPrep = {
  title: 'Peralatan',
  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 Peralatan',
    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 getCurrentToolsDetail = async (id: number | string) => {
  const result = await getDeviceDetail(id)
  if (result.success) {
    const currentValue = result.body?.data || {}
    recItem.value = currentValue
  }
}

const getUomList = async () => {
  const result = await getUoms()
  if (result.success) {
    const currentUoms = result.body?.data || []
    uoms.value = currentUoms.map((uom: Uom) => ({ value: uom.code || uom.erp_id, label: uom.name }))
  }
}

// Watch for row actions
watch([recId, recAction], () => {
  switch (recAction.value) {
    case ActionEvents.showDetail:
      getCurrentToolsDetail(recId.value)
      title.value = 'Detail Peralatan'
      isReadonly.value = true
      isFormEntryDialogOpen.value = true
      break
    case ActionEvents.showEdit:
      getCurrentToolsDetail(recId.value)
      title.value = 'Edit Peralatan'
      isReadonly.value = false
      isFormEntryDialogOpen.value = true
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})

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

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

    <Dialog
      v-model:open="isFormEntryDialogOpen"
      :title="!!recItem ? title : 'Tambah Peralatan'"
      size="lg"
      prevent-outside
    >
      <AppToolsEntryForm
        :schema="DeviceSchema"
        :values="recItem"
        :uoms="uoms"
        :is-loading="isProcessing"
        :is-readonly="isReadonly"
        @submit="
          (values: DeviceFormData, resetForm: any) => {
            if (recId > 0) {
              handleActionEdit(recId, values, getToolsList, resetForm, toast)
              return
            }
            handleActionSave(values, getToolsList, resetForm, toast)
          }
        "
        @cancel="handleCancelForm"
      />
    </Dialog>

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