<script setup lang="ts">
import type { Summary } from '~/components/pub/base/summary-card.type'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/nav/types'
import { Calendar, Hospital, UserCheck, UsersRound } from 'lucide-vue-next'
import SummaryCard from '~/components/pub/base/summary-card/summary-card.vue'
import Header from '~/components/pub/custom-ui/nav-header/prep.vue'

const data = ref([])

const refSearchNav: RefSearchNav = {
  onClick: () => {
    // open filter modal
  },
  onInput: (_val: string) => {
    // filter patient list
  },
  onClear: () => {
    // clear url param
  },
}

// Loading state management
const isLoading = reactive({
  summary: false,
  table: false,
})
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)

const hreaderPrep: HeaderPrep = {
  title: 'Pasien',
  icon: 'i-lucide-users',
  addNav: {
    label: 'Tambah',
    onClick: () => navigateTo('/patient/add'),
  },
}

// Initial/default data structure
const summaryData: Summary[] = [
  {
    title: 'Total Pasien',
    icon: UsersRound,
    metric: 23,
    trend: 15,
    timeframe: 'daily',
  },
  {
    title: 'Pasien Aktif',
    icon: UserCheck,
    metric: 100,
    trend: 9,
    timeframe: 'daily',
  },
  {
    title: 'Kunjungan Hari Ini',
    icon: Calendar,
    metric: 52,
    trend: 1,
    timeframe: 'daily',
  },
  {
    title: 'Peserta BPJS',
    icon: Hospital,
    metric: 71,
    trend: -3,
    timeframe: 'daily',
  },
]

// API call function
async function getPatientSummary() {
  try {
    isLoading.summary = true

    await new Promise((resolve) => setTimeout(resolve, 500))
  } catch (error) {
    console.error('Error fetching patient summary:', error)
    // Keep default/existing data on error
  } finally {
    isLoading.summary = false
  }
}

async function getPatientList() {
  const resp = await xfetch('/api/v1/patient')
  console.log('data patient', resp)
  if (resp.success) {
    data.value = (resp.body as Record<string, any>).data
  }
}

onMounted(() => {
  getPatientSummary()
  getPatientList()
})

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
</script>

<template>
  <Header :prep="{ ...hreaderPrep }" :ref-search-nav="refSearchNav" />
  <div class="my-4 flex flex-1 flex-col gap-4 md:gap-8">
    <div class="grid gap-4 md:grid-cols-2 md:gap-8 lg:grid-cols-4">
      <template v-if="isLoading.summary">
        <SummaryCard v-for="n in 4" :key="n" is-skeleton />
      </template>
      <template v-else>
        <SummaryCard v-for="card in summaryData" :key="card.title" :stat="card" />
      </template>
    </div>
    <AppPatientList :data="data" />
  </div>
</template>
