<template>
  <div class="h-full min-h-0 flex flex-col">
    <AppHeader title="Patient History" />

    <div class="flex-1 p-4 sm:p-6 lg:p-8 max-w-5xl mx-auto w-full">
      <!-- Search when no patient selected -->
      <div v-if="!patientId" class="card">
        <h2 class="text-lg font-semibold mb-4">Find Patient</h2>
        <PatientSearch v-model="selectedPatientId" />
        <button
          v-if="selectedPatientId"
          @click="router.push(`/patients/${selectedPatientId}/history`)"
          class="btn-primary mt-4"
        >
          View History
        </button>
      </div>

      <!-- History view -->
      <div v-else>
        <div v-if="batchStore.loading" class="text-gray-500 text-center py-8">
          Loading history...
        </div>

        <div v-else-if="batchStore.error" class="text-clinical-danger text-center py-8">
          {{ batchStore.error }}
        </div>

        <div v-else-if="history">
          <!-- Summary stats -->
          <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
            <div class="card-elevated text-center">
              <p class="text-2xl font-bold">{{ history.totalBatches }}</p>
              <p class="text-xs text-gray-500">Total Batches</p>
            </div>
            <div class="card-elevated text-center">
              <p class="text-2xl font-bold text-green-700">{{ history.promotedBatches }}</p>
              <p class="text-xs text-gray-500">Promoted</p>
            </div>
            <div class="card-elevated text-center">
              <p class="text-2xl font-bold text-orange-600">{{ history.pendingBatches }}</p>
              <p class="text-xs text-gray-500">Pending</p>
            </div>
            <div class="card-elevated text-center">
              <p class="text-2xl font-bold text-gray-400">{{ history.supersededBatches }}</p>
              <p class="text-xs text-gray-500">Superseded</p>
            </div>
          </div>

          <!-- Timeline -->
          <div class="space-y-4">
            <div
              v-for="entry in history.entries"
              :key="entry.batchId"
              :data-batch-id="entry.batchId"
              class="card relative transition-all"
              :class="{
                'border-l-4 border-l-green-500': entry.status === 'PROMOTED' && !entry.hasBeenSuperseded,
                'border-l-4 border-l-gray-300': entry.hasBeenSuperseded,
                'border-l-4 border-l-blue-500': entry.isCorrection && !entry.hasBeenSuperseded,
                'border-l-4 border-l-yellow-500': !['PROMOTED', 'CANCELLED'].includes(entry.status) && !entry.hasBeenSuperseded,
              }"
            >
              <!-- Header row -->
              <div class="flex flex-wrap items-center gap-2 mb-3">
                <span class="font-mono text-xs text-gray-600">
                  {{ entry.batchId.substring(0, 8) }}...
                </span>
                <span :class="statusBadgeClass(entry.status)" class="status-badge">
                  {{ formatStatus(entry.status) }}
                </span>
                <span class="status-badge bg-gray-100 text-gray-700">
                  {{ formatBatchType(entry.batchType) }}
                </span>
                <span
                  v-if="entry.isCorrection"
                  class="status-badge bg-blue-100 text-blue-800"
                >
                  Correction
                </span>
                <span
                  v-if="entry.hasBeenSuperseded"
                  class="status-badge bg-gray-200 text-gray-500"
                >
                  Superseded
                </span>
              </div>

              <!-- Supersession chain info -->
              <div
                v-if="entry.isCorrection && entry.supersedesBatchId"
                class="text-xs text-blue-700 bg-blue-50 rounded px-3 py-2 mb-3"
              >
                Corrects batch
                <button
                  @click="scrollToBatch(entry.supersedesBatchId!)"
                  class="font-mono underline hover:text-blue-900"
                >
                  {{ entry.supersedesBatchId.substring(0, 8) }}...
                </button>
              </div>
              <div
                v-if="entry.hasBeenSuperseded && entry.supersededByBatchId"
                class="text-xs text-gray-500 bg-gray-50 rounded px-3 py-2 mb-3"
              >
                Superseded by
                <button
                  @click="scrollToBatch(entry.supersededByBatchId!)"
                  class="font-mono underline hover:text-gray-700"
                >
                  {{ entry.supersededByBatchId.substring(0, 8) }}...
                </button>
              </div>

              <!-- Observation counts -->
              <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm mb-3">
                <div>
                  <span class="text-gray-500">Draft obs:</span>
                  <span class="font-medium ml-1">{{ entry.draftObservationCount }}</span>
                </div>
                <div>
                  <span class="text-gray-500">Live obs:</span>
                  <span class="font-medium ml-1" :class="{ 'line-through text-gray-400': entry.hasBeenSuperseded }">
                    {{ entry.liveObservationCount }}
                  </span>
                </div>
                <div v-if="entry.supersededObservationCount > 0">
                  <span class="text-gray-500">Superseded obs:</span>
                  <span class="font-medium ml-1 text-gray-400">{{ entry.supersededObservationCount }}</span>
                </div>
                <div v-if="entry.promotionEncounterId">
                  <span class="text-gray-500">Encounter:</span>
                  <span class="font-mono text-xs ml-1">{{ entry.promotionEncounterId.substring(0, 8) }}...</span>
                </div>
              </div>

              <!-- People & dates -->
              <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-gray-500">
                <div>Created: {{ new Date(entry.createdAt).toLocaleString() }}</div>
                <div v-if="entry.promotedAt">
                  Promoted: {{ new Date(entry.promotedAt).toLocaleString() }}
                </div>
                <div v-if="entry.enteredByUserName">
                  Entered by: {{ entry.enteredByUserName }}
                </div>
                <div v-if="entry.verifiedByUserName">
                  Verified by: {{ entry.verifiedByUserName }}
                </div>
                <div v-if="entry.approvedByUserName">
                  Approved by: {{ entry.approvedByUserName }}
                </div>
              </div>

              <!-- Audit trail (collapsible) -->
              <details v-if="entry.auditTrail.length > 0" class="mt-3">
                <summary class="text-xs text-primary-600 cursor-pointer hover:text-primary-800">
                  Audit trail ({{ entry.auditTrail.length }} events)
                </summary>
                <div class="mt-2 space-y-1 pl-3 border-l-2 border-gray-200">
                  <div
                    v-for="(event, idx) in entry.auditTrail"
                    :key="idx"
                    class="text-xs text-gray-600"
                  >
                    <span class="font-medium">{{ formatEventType(event.eventType) }}</span>
                    <span class="text-gray-400 ml-2">
                      {{ new Date(event.occurredAt).toLocaleString() }}
                    </span>
                    <span class="ml-2">by {{ event.actorName }}</span>
                  </div>
                </div>
              </details>

              <!-- Create Correction button for promoted, non-superseded batches -->
              <div
                v-if="entry.status === 'PROMOTED' && !entry.hasBeenSuperseded"
                class="mt-3 pt-3 border-t border-gray-100"
              >
                <button
                  @click="createCorrection(entry)"
                  class="text-sm text-primary-600 hover:text-primary-800 font-medium"
                >
                  Create Correction
                </button>
              </div>
            </div>
          </div>

          <div v-if="history.entries.length === 0" class="text-gray-500 text-center py-8">
            No digitization history for this patient.
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useBatchStore } from '../stores/batches'
import AppHeader from '../components/AppHeader.vue'
import PatientSearch from '../components/PatientSearch.vue'
import type { PatientDigitizationHistoryResponse, DigitizationHistoryEntry } from '../types'

const props = defineProps<{ patientId?: string }>()

const route = useRoute()
const router = useRouter()
const batchStore = useBatchStore()

const patientId = ref(props.patientId ?? (route.params.patientId as string | undefined))
const selectedPatientId = ref<string | undefined>()
const history = ref<PatientDigitizationHistoryResponse | null>(null)

watch(
  () => props.patientId ?? (route.params.patientId as string | undefined),
  async (id) => {
    patientId.value = id
    if (id) {
      history.value = await batchStore.getPatientHistory(id)
    }
  },
  { immediate: true },
)

function formatBatchType(type: string): string {
  return type.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
}

function formatStatus(status: string): string {
  return status.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
}

function formatEventType(type: string): string {
  return type.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
}

function statusBadgeClass(status: string): string {
  const classes: Record<string, string> = {
    UPLOADED: 'bg-gray-100 text-gray-800',
    IN_ENTRY: 'bg-yellow-100 text-yellow-800',
    PENDING_VERIFICATION: 'bg-orange-100 text-orange-800',
    REJECTED: 'bg-red-100 text-red-800',
    VERIFIED: 'bg-blue-100 text-blue-800',
    AWAITING_CLINICAL_APPROVAL: 'bg-purple-100 text-purple-800',
    APPROVED: 'bg-green-100 text-green-800',
    PROMOTED: 'bg-emerald-100 text-emerald-800',
    CANCELLED: 'bg-gray-200 text-gray-500',
  }
  return classes[status] ?? 'bg-gray-100 text-gray-800'
}

function scrollToBatch(batchId: string) {
  const el = document.querySelector(`[data-batch-id="${batchId}"]`)
  if (el) {
    el.scrollIntoView({ behavior: 'smooth', block: 'center' })
    el.classList.add('ring-2', 'ring-primary-400')
    setTimeout(() => el.classList.remove('ring-2', 'ring-primary-400'), 2000)
  }
}

function createCorrection(entry: DigitizationHistoryEntry) {
  router.push({
    path: '/intake',
    query: {
      supersedesBatchId: entry.batchId,
      patientId: patientId.value,
      batchType: entry.batchType,
    },
  })
}
</script>
