<script setup>
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
import * as reconciliationApi from '@/api/reconciliation'
import Button from '@/components/ui/Button.vue'
import Badge from '@/components/ui/Badge.vue'
import Skeleton from '@/components/ui/Skeleton.vue'
import EmptyState from '@/components/ui/EmptyState.vue'
import {
  RECONCILIATION_SECTIONS,
  formatReconciliationTimestamp,
} from '@/composables/reconciliationFormat'

const includeResolved = ref(false)
const loading = ref(true)
const error = ref('')
const sections = ref([])

async function loadSection(section) {
  const result = await reconciliationApi.fetchReconciliationAlerts({
    checkType: section.checkType,
    resolved: includeResolved.value ? undefined : false,
    pageSize: 100,
  })
  return {
    ...section,
    items: result.items ?? [],
    totalCount: result.totalCount ?? 0,
  }
}

async function load() {
  loading.value = true
  error.value = ''
  try {
    sections.value = await Promise.all(RECONCILIATION_SECTIONS.map(loadSection))
  } catch (err) {
    error.value = err.message
    sections.value = []
  } finally {
    loading.value = false
  }
}

function onToggleResolved() {
  load()
}

onMounted(load)
</script>

<template>
  <div>
    <div class="mb-4 flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="text-xl font-bold dark:text-white">Data Quality</h1>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          Reconciliation findings from periodic workflow checks across the ward.
        </p>
      </div>
      <label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
        <input
          v-model="includeResolved"
          type="checkbox"
          class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          @change="onToggleResolved"
        >
        Include resolved
      </label>
    </div>

    <p v-if="error" class="mb-4 text-sm text-red-600 dark:text-red-400">{{ error }}</p>

    <Skeleton v-if="loading" :rows="10" />

    <div v-else class="space-y-8">
      <section
        v-for="section in sections"
        :key="section.checkType"
        class="rounded-lg border border-gray-200 dark:border-gray-700"
      >
        <div class="border-b border-gray-200 px-4 py-3 dark:border-gray-700">
          <div class="flex flex-wrap items-center justify-between gap-2">
            <h2 class="font-semibold text-gray-900 dark:text-white">{{ section.title }}</h2>
            <Badge :variant="section.totalCount > 0 ? 'warning' : 'success'">
              {{ section.totalCount }} finding{{ section.totalCount === 1 ? '' : 's' }}
            </Badge>
          </div>
          <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">{{ section.description }}</p>
        </div>

        <EmptyState
          v-if="section.items.length === 0"
          message="No findings in this category"
        />

        <div v-else class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200 text-sm dark:divide-gray-700">
            <thead class="bg-gray-50 dark:bg-gray-800">
              <tr class="text-left text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">
                <th class="px-4 py-3">Detected</th>
                <th class="px-4 py-3">Details</th>
                <th class="px-4 py-3">Status</th>
                <th class="px-4 py-3 text-right">Patient</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
              <tr v-for="item in section.items" :key="item.id">
                <td class="px-4 py-3 text-gray-700 dark:text-gray-300">
                  {{ formatReconciliationTimestamp(item.createdAt) }}
                </td>
                <td class="px-4 py-3 text-gray-700 dark:text-gray-300">{{ item.details }}</td>
                <td class="px-4 py-3">
                  <Badge :variant="item.resolvedAt ? 'success' : 'warning'">
                    {{ item.resolvedAt ? 'Resolved' : 'Open' }}
                  </Badge>
                </td>
                <td class="px-4 py-3 text-right">
                  <RouterLink
                    v-if="item.encounterId"
                    :to="`/patients/${item.encounterId}`"
                    class="text-sm font-medium text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                  >
                    View patient
                  </RouterLink>
                  <span v-else class="text-gray-400">—</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </div>

    <div class="mt-4">
      <Button size="sm" variant="secondary" @click="load">Refresh</Button>
    </div>
  </div>
</template>
