<script setup lang="ts">
// Components
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import List from '~/components/app/initial-nursing/list.vue'
import Preview from '~/components/app/initial-nursing/preview.vue'

// Helpers
import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'

// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'

// Handlers
import {
  recId,
  recAction,
  recItem,
  isReadonly,
  isProcessing,
  isFormEntryDialogOpen,
  isRecordConfirmationOpen,
  onResetState,
  handleActionSave,
  handleActionEdit,
  handleActionRemove,
  handleCancelForm,
} from '~/handlers/soapi-early.handler'

// Services
import { getList, getDetail } from '~/services/soapi-early.service'

// Models
import type { Encounter } from '~/models/encounter'

// Props
interface Props {
  encounter: Encounter
}
const props = defineProps<Props>()
const emits = defineEmits(['add', 'edit'])
const route = useRoute()

const { recordId } = useQueryCRUDRecordId()
const { goToEntry, backToList } = useQueryCRUDMode('mode')

let units = ref<{ value: string; label: string }[]>([])
const encounterId = ref<number>(props?.encounter?.id || 0)
const title = ref('')
const id = route.params.id
const descData = ref({})

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getMyList,
} = usePaginatedList({
  fetchFn: async ({ page, search }) => {
    const result = await getList({
      'encounter-id': id,
      'type-code': 'early-nursery',
      includes: 'encounter',
      search,
      page,
    })
    console.log('masukkk', result)
    if (result.success) {
      data.value = result.body.data
    }
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'initial-nursing',
})

const headerPrep: HeaderPrep = {
  title: 'Kajian Awal Keperawatan',
  icon: 'i-lucide-box',
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (value: string) => {
      searchInput.value = value
    },
    onClick: () => {},
    onClear: () => {},
  },
  addNav: {
    label: 'Tambah',
    icon: 'i-lucide-plus',
    onClick: () => {
      goToEntry()
      emits('add')
    },
  },
}

const today = new Date()

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

const getMyDetail = async (id: number | string) => {
  const result = await getDetail(id)
  if (result.success) {
    const currentValue = result.body?.data || {}
    recItem.value = currentValue
    isFormEntryDialogOpen.value = true
  }
}

const mappedData = computed(() => {
  if (!data.value || data.value.length === 0) return []

  const raw = data.value[0]

  // Pastikan raw.value adalah string JSON
  let parsed: any = {}
  try {
    parsed = JSON.parse(raw.value || '{}')
  } catch (err) {
    console.error('JSON parse error:', err)
    return []
  }

  // Ambil listProblem
  const list = parsed.listProblem || []
  const textData = parsed

  // Untuk keamanan: pastikan selalu array
  if (!Array.isArray(list)) return []

  return { list, textData }
})

// Watch for row actions when recId or recAction changes
watch([recId, recAction], () => {
  switch (recAction.value) {
    case ActionEvents.showDetail:
      getMyDetail(recId.value)
      title.value = 'Detail Konsultasi'
      isReadonly.value = true
      break
    case ActionEvents.showEdit:
      emits('edit')
      recordId.value = recId.value
      console.log('recordId', recId.value)
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})

onMounted(async () => {
  await getMyList()
})
</script>

<template>
  <Header
    v-model="searchInput"
    :prep="headerPrep"
    :ref-search-nav="headerPrep.refSearchNav"
    @search="handleSearch"
    class="mb-4 xl:mb-5"
  />

  <Preview :preview="mappedData.textData" />

  <h2 class="my-3 p-1 font-semibold">C. Daftar Masalah Keperawatan</h2>
  <List :data="mappedData.list || []" />
  <!-- :pagination-meta="paginationMeta" -->
  <!-- @page-change="handlePageChange" -->

  <!-- Record Confirmation Modal -->
  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="() => handleActionRemove(recId, getMyList, toast)"
    @cancel=""
  >
    <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>
</template>
