<script setup lang="ts">
import type { DataTableLoader } from '~/components/pub/base/data-table/type';
import type { ServiceStatus } from '~/components/pub/base/service-status/type'
import type { Summary } from '~/components/pub/base/summary-card/type'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/custom-ui/data/types'
import { useUrlSearchParams } from '@vueuse/core'
import { CircleCheckBig, CircleDashed, CircleX, Ellipsis, Search, Send } from 'lucide-vue-next'
import Header from '~/components/pub/custom-ui/nav-header/header.vue';

// State management
const data = ref([])
const isLoading = reactive<DataTableLoader>({
  satusehatConn: true,
  isTableLoading: false,
})

const params = useUrlSearchParams('history', {
  initialValue: {
    search: '',
    status: '',
    resource_type: 'all',
    date_from: '',
    date_to: '',
    page: 1,
    limit: 10,
  },
  removeFalsyValues: true,
})

// Pagination state
const pagination = ref({
  total: 0,
  page: 1,
  limit: 10,
  total_pages: 0,
  has_next: false,
  has_prev: false,
})

// API function to fetch data
async function fetchData() {
  try {
    isLoading.isTableLoading = true
    const response: any = await $fetch('/api/v1/satusehat/list', {
      method: 'POST',
      body: {
        status: params.status !== '' ? Number(params.status) : undefined,
        resource_type: params.resource_type,
        date_from: params.date_from,
        date_to: params.date_to,
        search: params.search,
        page: params.page,
        limit: params.limit,
      },
    })

    if (response.success) {
      data.value = response.data
      pagination.value = response.meta
    }
  } catch (error) {
    console.error('Error fetching data:', error)
  } finally {
    isLoading.isTableLoading = false
  }
}

// Debounced search function

const refSearchNav: RefSearchNav = {
  onClick: () => {
    // open filter modal
  },
  onInput: (val: string) => {
  },
  onClear: () => {
  },
}

const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)

function onResourceTypeChange(resourceType: string) {
  params.resource_type = resourceType
  params.page = 1
  fetchData()
}

const headerPrep: HeaderPrep = {
  title: 'SATUSEHAT Integration',
  icon: 'i-lucide-box',
  addNav: {
    label: 'Kirim Resource',
    icon: 'i-lucide-send',
    // onClick: () => navigateTo('/patient/add'),
  },
}

// SATUSEHAT Service integration
const service = reactive<ServiceStatus>({
  serviceName: 'SATUSEHAT',
  serviceDesc: 'SATUSEHAT - FHIR R4 Compliant',
  sessionActive: false,
  status: 'connecting',
  isSkeleton: false,
})

// Initial/default data structure
const summaryData: Summary[] = [
  {
    title: 'Resource Terkirim',
    icon: Send,
    metric: 1245,
    trend: 0,
    timeframe: 'daily',
  },
  {
    title: 'Sync Success',
    icon: CircleCheckBig,
    metric: '97%',
    trend: 0,
    timeframe: 'daily',
  },
  {
    title: 'Pending Queue',
    icon: CircleDashed,
    metric: 32,
    trend: 0,
    timeframe: 'daily',
  },
  {
    title: 'Failed Items',
    icon: CircleX,
    metric: 10,
    trend: 0,
    timeframe: 'daily',
  },
]

async function callSatuSehat() {
  try {
    await new Promise((resolve) => setTimeout(resolve, 500))
    service.status = 'connected'
    // service.status = 'error'
    service.sessionActive = true
    // service.sessionActive = false
  } finally {
    isLoading.satusehatConn = false
  }
}

// Watch for tab changes
watch(() => params.resource_type, (newType) => {
  onResourceTypeChange(newType)
})

onMounted(async () => {
  await callSatuSehat()
  await fetchData()
})

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

const tabs = [
  {
    value: 'all',
    label: 'Semua Resource',
  },
  {
    value: 'patient',
    label: 'Patient',
  },
  {
    value: 'encounter',
    label: 'Encounter',
  },
  {
    value: 'observation',
    label: 'Observation',
  },
]

// Status filter options
const statusOptions = [
  { value: '0', label: 'Failed' },
  { value: '1', label: 'Pending' },
  { value: '2', label: 'Success' },
]
const actions = [
  {
    value: 'export',
    label: 'Ekspor',
    icon: 'i-lucide-download',
  },
]

// Sync activeTabFilter with filters.resource_type
const activeTabFilter = computed({
  get: () => params.resource_type,
  set: (value) => {
    params.resource_type = value
  },
})
</script>

<template>
  <Header :prep="headerPrep" />
  <div class="my-4 flex flex-1 flex-col gap-3 md:gap-4">
    <PubBaseServiceStatus v-bind="service" />
    <AppSatusehatCardSummary :is-loading="isLoading.satusehatConn!" :summary-data="summaryData" />
  </div>
  <div class="rounded-md border p-4">
    <h2 class="text-md font-semibold py-2">FHIR Resource</h2>
    <Tabs v-model="activeTabFilter">
      <div class="scrollbar-hide overflow-x-auto flex gap-2 justify-between">
        <TabsList>
          <TabsTrigger v-for="tab in tabs" :key="tab.value" :value="tab.value"
            class="flex-shrink-0 px-4 py-2 text-sm font-medium data-[state=active]:bg-green-600 data-[state=inactive]:bg-gray-100 data-[state=active]:text-white data-[state=inactive]:text-gray-700">
            {{ tab.label }}
          </TabsTrigger>
        </TabsList>
        <div class="flex gap-2 items-center">

          <!-- Search Input -->

          <div class="relative w-full max-w-sm">

            <Dialog>
              <DialogTrigger>
                <Input id="search" v-model="params.search" type="text" placeholder="Cari pasien..." class="pl-3 h-9" />
              </DialogTrigger>
              <DialogContent>
                <DialogHeader class="border-b-1">
                  <DialogTitle class="pb-2">Pencarian</DialogTitle>
                </DialogHeader>
                <Form>
                  <FormField v-slot="{ componentField }" name="username">
                    <FormItem>
                      <FormLabel>Pasien</FormLabel>
                      <FormControl>
                        <Input type="text" placeholder="nama pasien, id pasien" v-bind="componentField" />
                      </FormControl>
                    </FormItem>
                  </FormField>
                  <FormField v-slot="{ componentField }" name="status">
                    <FormItem>
                      <FormLabel>Status</FormLabel>
                      <FormControl>
                        <Select>
                          <SelectTrigger class="bg-white border border-gray-300">
                            <SelectValue class="text-gray-400" placeholder="-- select item" />
                          </SelectTrigger>
                          <SelectContent class="bg-white ">
                            <SelectItem value="0">
                              Gagal
                            </SelectItem>
                            <SelectItem value="1">
                              Pending
                            </SelectItem>
                            <SelectItem value="2">
                              Terkirim
                            </SelectItem>
                          </SelectContent>
                        </Select>
                      </FormControl>
                    </FormItem>
                  </FormField>
                  <FormField v-slot="{ componentField }" name="fhirId">
                    <FormItem>
                      <FormLabel>FHIR ID</FormLabel>
                      <FormControl>
                        <Input type="text" placeholder="fhir id" v-bind="componentField" />
                      </FormControl>
                    </FormItem>
                  </FormField>
                </Form>

                <DialogFooter>
                  <Button variant="outline">
                    Reset
                  </Button>
                  <Button>
                    Apply
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>

          <!-- Action Buttons -->
          <AppSatusehatButtonAction v-for="action in actions" :key="action.value" :icon="action.icon"
            :text="action.label" />
        </div>
      </div>
      <div class="mt-4">
        <TabsContent v-for="tab in tabs" :key="`content-${tab.value}`" :value="tab.value">
          <div class="rounded-md border p-4">
            <!-- <Ellipsis v-if="isLoading.satusehatConn || isLoading.dataList" -->
            <!-- class="size-6 animate-pulse text-muted-foreground mx-auto" /> -->
            <AppSatusehatList v-if="!isLoading.satusehatConn" :data="data" />

            <!-- Pagination -->
            <div v-if="!isLoading.satusehatConn && !isLoading.isTableLoading && pagination.total > 0"
              class="mt-4 flex justify-between items-center">
              <div class="text-sm text-muted-foreground">
                Menampilkan {{ ((pagination.page - 1) * pagination.limit) + 1 }} -
                {{ Math.min(pagination.page * pagination.limit, pagination.total) }}
                dari {{ pagination.total }} data
              </div>
              <div class="flex gap-2">
                <Button v-if="pagination.has_prev" variant="outline" size="sm" @click="params.page--; fetchData()">
                  Sebelumnya
                </Button>
                <Button v-if="pagination.has_next" variant="outline" size="sm" @click="params.page++; fetchData()">
                  Selanjutnya
                </Button>
              </div>
            </div>
          </div>
        </TabsContent>
      </div>
    </Tabs>
  </div>
</template>
