<script setup lang="ts">
import type { HeaderPrep } from '~/components/pub/my-ui/data/types'
import AppUnitEntryForm from '~/components/app/unit/entry-form.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import { ActionEvents } from '~/components/pub/my-ui/data/types'
import Header from '~/components/pub/my-ui/nav-header/header.vue'
import { usePaginatedList } from '~/composables/usePaginatedList'
import { schemaConf, unitConf } from './entry'

// #region State & Computed
// Dialog state
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)

// Table action rowId provider
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)

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

// Menggunakan composable untuk pagination
const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getUnitList,
} = usePaginatedList({
  fetchFn: fetchUnitData,
  entityName: 'unit',
})

const headerPrep: HeaderPrep = {
  title: 'Unit',
  icon: 'i-lucide-box',
  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 Unit',
    icon: 'i-lucide-send',
    onClick: () => {
      isFormEntryDialogOpen.value = true
    },
  },
}

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

// #region Functions

async function handleDeleteRow(record: any) {
  try {
    // TODO : hit backend request untuk delete
    console.log('Deleting record:', record)

    // Simulate API call
    // const response = await xfetch(`/api/v1/unit/${record.id}`, {
    //   method: 'DELETE'
    // })

    // Refresh data setelah berhasil delete
    await getUnitList()

    // 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
  }
}

// #endregion region

// #region Form event handlers

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

async function onSubmitForm(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/unit', {
    //   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 getUnitList()

    // TODO: Show success message
    console.log('Unit 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)
    }
  }
}
// #endregion

// #region Watchers

// 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
  }
})

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

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

<template>
  <Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
  <AppUnitList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />

  <Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Unit" size="lg" prevent-outside>
    <AppUnitEntryFormPrev
      :unit="unitConf" :schema="schemaConf" :initial-values="{ name: '', code: '', parentId: '' }"
      @submit="onSubmitForm" @cancel="onCancelForm"
/>
  </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?.firstName"><strong>Nama:</strong> {{ record.firstName }}</p>
        <p v-if="record?.code"><strong>Kode:</strong> {{ record.cellphone }}</p>
      </div>
    </template>
  </RecordConfirmation>
</template>

<style scoped>
/* component style */
</style>
