<script setup lang="ts">
import type { HeaderPrep } from '~/components/pub/custom-ui/data/types'
import AppDivisionEntry from './entry.vue'
import Dialog from '~/components/pub/base/modal/dialog.vue'
import RecordConfirmation from '~/components/pub/custom-ui/confirmation/record-confirmation.vue'
import { ActionEvents } from '~/components/pub/custom-ui/data/types'
import Header from '~/components/pub/custom-ui/nav-header/header.vue'
import { usePaginatedList } from '~/composables/usePaginatedList'

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

// Fungsi untuk fetch data division
async function fetchDivisionData(params: any) {
  // Prepare query parameters for pagination and search
  const urlParams = new URLSearchParams({
    'page-number': params.page.toString(),
    'page-size': params.pageSize.toString(),
  })

  if (params.q) {
    urlParams.append('search', params.q)
  }

  // return await xfetch(`/api/v1/patient?${urlParams.toString()}`)
  return await xfetch('/api/v1/_dev/division/list')
}

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

const headerPrep: HeaderPrep = {
  title: 'Divisi',
  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 Divisi',
    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/division/${record.id}`, {
    //   method: 'DELETE'
    // })

    // Refresh data setelah berhasil delete
    await getDivisionList()

    // 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/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 getDivisionList()

    // TODO: Show success message
    console.log('Division 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>
  <div class="rounded-md border p-4">
    <Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
    <AppDivisonList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />

    <Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Divisi" size="lg" prevent-outside>
      <AppDivisionEntry
        :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>
  </div>
</template>

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