<script setup lang="ts">
import type { HeaderPrep } from '~/components/pub/custom-ui/data/types'
import AppSubspecialistEntryForm from '~/components/app/subspecialist/entry-form.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'
import { createFilteredUnitConf, installationConf, schemaConf, specialistConf, 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, unit, dan specialist yang dipilih di form
const selectedInstallationId = ref<string>('')
const selectedUnitId = 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: getSubSpecialistList,
} = usePaginatedList({
  fetchFn: fetchSubSpecialistData,
  entityName: 'subspecialist',
})

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

    // Refresh data setelah berhasil delete
    await getSubSpecialistList()

    // 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
  selectedInstallationId.value = ''
  selectedUnitId.value = ''

  setTimeout(() => {
    resetForm()
  }, 500)
}

function onInstallationChanged(installationId: string) {
  selectedInstallationId.value = installationId
}

function onUnitChanged(unitId: string) {
  selectedUnitId.value = unitId
}

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

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

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

    // Refresh data after successful submission
    await getSubSpecialistList()

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

// #endregion
</script>

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

    <Dialog v-model:open="isFormEntryDialogOpen" :title="headerPrep.addNav?.label!" size="lg" prevent-outside>
      <AppSubspecialistEntryForm
        :installation="installationConf"
        :unit="filteredUnitConf"
        :specialist="specialistConf"
        :schema="schemaConf"
        :initial-values="{ name: '', code: '', installationId: '', unitId: '', specialistId: '' }"
        @submit="onSubmitForm"
        @cancel="onCancelForm"
        @installation-changed="onInstallationChanged"
        @unit-changed="onUnitChanged"
      />
    </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?.name"><strong>Nama:</strong> {{ record.name }}</p>
          <p v-if="record?.code"><strong>Kode:</strong> {{ record.code }}</p>
          <p v-if="record?.specialist"><strong>Specialist:</strong> {{ record.specialist?.name }}</p>
        </div>
      </template>
    </RecordConfirmation>
  </div>
</template>
