<script setup lang="ts">
import { DeviceSchema, type DeviceFormData } from '~/schemas/device'
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'

const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)

const uoms = [
  { value: 'uom-1', label: 'Satuan 1' },
  { value: 'uom-2', label: 'Satuan 2' },
  { value: 'uom-3', label: 'Satuan 3' },
]
const items = [
  { value: 'item-1', label: 'Item 1' },
  { value: 'item-2', label: 'Item 2' },
  { value: 'item-3', label: 'Item 3' },
]

async function fetchDeviceData(params: any) {
  const endpoint = transform('/api/v1/device', params)
  return await xfetch(endpoint)
}

// Menggunakan composable untuk pagination
const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getDeviceList,
} = usePaginatedList({
  fetchFn: fetchDeviceData,
  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: () => {
      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:
      // TODO: Handle edit action
      // isFormEntryDialogOpen.value = true
      break
    case ActionEvents.showConfirmDelete:
      // Trigger confirmation modal open
      isRecordConfirmationOpen.value = true
      break
  }
})

const handleDeleteRow = async (record: any) => {
  try {
    // TODO : hit backend request untuk delete
    console.log('Deleting record:', record)
    // Simulate API call
    // const response = await xfetch(`/api/v1/device/${record.id}`, {
    //   method: 'DELETE'
    // })

    // Refresh data setelah berhasil delete
    await getDeviceList()

    // TODO: Show success message
    console.log('Record deleted successfully')
  } catch (error) {
    console.error('Error deleting record:', error)
    // TODO: Show error message
  } finally {
    // Reset record state
    recId.value = 0
    recAction.value = ''
    recItem.value = null
  }
}

const onCancelForm = (resetForm: () => void) => {
  isFormEntryDialogOpen.value = false
  setTimeout(() => {
    resetForm()
  }, 500)
}

const onSubmitForm = async (values: any, resetForm: () => void) => {
  let isSuccess = false
  try {
    // TODO: Implement form submission logic
    console.log('Form submitted:', values)

    // Simulate API call
    // const response = await xfetch('/api/v1/division', {
    //   method: 'POST',
    //   body: JSON.stringify(values)
    // })

    // If successful, mark as success and close dialog
    isFormEntryDialogOpen.value = false
    isSuccess = true

    // Refresh data after successful submission
    await getDeviceList()

    // TODO: Show success message
    console.log('Device created successfully')
  } catch (error: unknown) {
    console.warn('Error submitting form:', error)
    isSuccess = false
    // Don't close dialog or reset form on error
    // TODO: Show error message to user
  } finally {
    if (isSuccess) {
      setTimeout(() => {
        resetForm()
      }, 500)
    }
  }
}

// Handle confirmation result
const handleConfirmDelete = (record: any, action: string) => {
  console.log('Confirmed action:', action, 'for record:', record)
  handleDeleteRow(record)
}

const handleCancelConfirmation = () => {
  // Reset record state when cancelled
  recId.value = 0
  recAction.value = ''
  recItem.value = null
}
</script>

<template>
  <div class="rounded-md border 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="Tambah Peralatan" size="lg" prevent-outside>
      <AppToolsEntryForm :schema="DeviceSchema" :uoms="uoms" :items="items" @back="onCancelForm" @submit="onSubmitForm" />
    </Dialog>

    <!-- Record Confirmation Modal -->
    <RecordConfirmation
      v-model:open="isRecordConfirmationOpen"
      action="delete"
      :record="recItem"
      @confirm="handleConfirmDelete"
      @cancel="handleCancelConfirmation"
    >
      <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>
