<script setup lang="ts">
import type { HeaderPrep } from '~/components/pub/my-ui/data/types'
import AppSpecialistEntryForm from '~/components/app/specialist/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 { createFilteredUnitConf, installationConf, 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)

// State untuk tracking installation yang dipilih di form
const selectedInstallationId = ref<string>('')

// Computed untuk filtered unit berdasarkan installation yang dipilih
const filteredUnitConf = computed(() => {
  if (!selectedInstallationId.value) {
    return { ...unitConf, items: [] }
  }
  return createFilteredUnitConf(selectedInstallationId.value)
})

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getSpecialistList,
} = usePaginatedList({
  fetchFn: fetchSpecialistData,
  entityName: 'specialist',
})

const headerPrep: HeaderPrep = {
  title: 'Specialist',
  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 Specialist',
    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 fetchSpecialistData(params: any) {
  const endpoint = transform('/api/v1/patient', params)
  return await xfetch(endpoint)
}

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/Installation/${record.id}`, {
    //   method: 'DELETE'
    // })

    // Refresh data setelah berhasil delete
    await getSpecialistList()

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

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

// #region Form event handlers

function onCancelForm(resetForm: () => void) {
  isFormEntryDialogOpen.value = false
  // Reset installation selection ketika form dibatal
  selectedInstallationId.value = ''
  setTimeout(() => {
    resetForm()
  }, 500)
}

function onInstallationChanged(installationId: string) {
  // Update local state untuk trigger re-render filtered units
  selectedInstallationId.value = installationId

  // The filteredUnitConf computed will automatically update
  // based on the new selectedInstallationId value
}

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/Installation', {
    //   method: 'POST',
    //   body: JSON.stringify(values)
    // })

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

    // Reset installation selection ketika form berhasil submit
    selectedInstallationId.value = ''

    // Refresh data after successful submission
    await getSpecialistList()

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

// Note: Installation change logic is now handled by the entry-form component
// through the onInstallationChanged event handler
// #endregion
</script>

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

  <Dialog v-model:open="isFormEntryDialogOpen" :title="headerPrep.addNav?.label!" size="lg" prevent-outside>
    <AppSpecialistEntryFormPrev
      :installation="installationConf"
      :unit="filteredUnitConf"
      :schema="schemaConf"
      :disabled-unit="!selectedInstallationId"
      :initial-values="{ name: '', code: '', installationId: '', unitId: '' }"
      @submit="onSubmitForm"
      @cancel="onCancelForm"
      @installation-changed="onInstallationChanged"
    />
  </Dialog>

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