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

    <div class="flex-1 overflow-y-auto p-4 sm:p-6 lg:p-8">
      <div class="max-w-5xl mx-auto space-y-6">
        <div>
          <h1 class="text-[1.75rem] font-semibold text-ink-strong leading-tight tracking-tight">
            Patient History
          </h1>
          <p class="mt-1 text-sm text-ink-secondary">
            Digitization lineage, promotion attribution, and audit trail for a patient.
          </p>
        </div>

        <!-- Search when no patient selected -->
        <section v-if="!patientId" class="card space-y-4">
          <h2 class="text-base font-semibold text-ink-strong">Find Patient</h2>
          <p class="text-sm text-ink-secondary">Search by MRN or name.</p>
          <PatientSearch v-model="selectedPatientId" />
          <button
            v-if="selectedPatientId"
            type="button"
            class="btn-primary"
            @click="router.push(`/patients/${selectedPatientId}/history`)"
          >
            View History
          </button>
        </section>

        <!-- History view -->
        <div v-else class="space-y-6">
          <SkeletonBlock v-if="batchStore.loading" variant="table" :rows="4" />

          <InlineError
            v-else-if="batchStore.error"
            title="Could not load patient history"
            :message="batchStore.error"
            preserved="Your patient selection was preserved."
            retry-label="Retry"
            @retry="reloadHistory"
          />

          <template v-else-if="history">
            <!-- Summary -->
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
              <div class="card-elevated text-center py-4">
                <p class="text-2xl font-bold text-ink-strong tabular-nums">
                  {{ history.totalBatches }}
                </p>
                <p class="text-xs text-ink-secondary mt-1">Total Batches</p>
              </div>
              <div class="card-elevated text-center py-4">
                <p class="text-2xl font-bold text-clinical-safe tabular-nums">
                  {{ history.promotedBatches }}
                </p>
                <p class="text-xs text-ink-secondary mt-1">Promoted</p>
              </div>
              <div class="card-elevated text-center py-4">
                <p class="text-2xl font-bold text-clinical-warning tabular-nums">
                  {{ history.pendingBatches }}
                </p>
                <p class="text-xs text-ink-secondary mt-1">Pending</p>
              </div>
              <div class="card-elevated text-center py-4">
                <p class="text-2xl font-bold text-ink-disabled tabular-nums">
                  {{ history.supersededBatches }}
                </p>
                <p class="text-xs text-ink-secondary mt-1">Superseded</p>
              </div>
            </div>

            <EmptyState
              v-if="history.entries.length === 0"
              title="No digitization history for this patient."
              description="Uploaded and promoted batches will appear here as a timeline."
            />

            <!-- Timeline -->
            <div v-else class="space-y-4">
              <h2 class="text-base font-semibold text-ink-strong">Digitization timeline</h2>

              <article
                v-for="entry in history.entries"
                :key="entry.batchId"
                :data-batch-id="entry.batchId"
                class="card relative transition-shadow"
                :class="timelineAccentClass(entry)"
              >
                <!-- Header -->
                <div class="flex flex-wrap items-center gap-2 mb-3">
                  <span class="font-mono text-xs text-ink-secondary">
                    {{ entry.batchId.substring(0, 8) }}…
                  </span>
                  <StatusBadge :status="entry.status" />
                  <span class="status-badge bg-canvas text-ink border border-line">
                    {{ formatBatchType(entry.batchType) }}
                  </span>
                  <span
                    v-if="entry.isCorrection"
                    class="status-badge bg-primary-50 text-primary-800 border border-primary-100"
                  >
                    Correction
                  </span>
                  <span
                    v-if="entry.hasBeenSuperseded"
                    class="status-badge bg-canvas text-ink-disabled border border-line"
                  >
                    Superseded
                  </span>
                </div>

                <!-- Supersession chain -->
                <div
                  v-if="entry.isCorrection && entry.supersedesBatchId"
                  class="text-xs text-primary-800 bg-primary-50 border border-primary-100 rounded-input px-3 py-2 mb-3"
                >
                  Corrects batch
                  <button
                    type="button"
                    class="font-mono underline hover:text-primary-900"
                    @click="scrollToBatch(entry.supersedesBatchId!)"
                  >
                    {{ entry.supersedesBatchId.substring(0, 8) }}…
                  </button>
                </div>
                <div
                  v-if="entry.hasBeenSuperseded && entry.supersededByBatchId"
                  class="text-xs text-ink-secondary bg-canvas border border-line rounded-input px-3 py-2 mb-3"
                >
                  Superseded by
                  <button
                    type="button"
                    class="font-mono underline hover:text-ink-strong"
                    @click="scrollToBatch(entry.supersededByBatchId!)"
                  >
                    {{ entry.supersededByBatchId.substring(0, 8) }}…
                  </button>
                </div>

                <!-- Observation counts -->
                <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm mb-4">
                  <div>
                    <span class="text-ink-secondary">Draft obs</span>
                    <p class="font-medium text-ink-strong">{{ entry.draftObservationCount }}</p>
                  </div>
                  <div>
                    <span class="text-ink-secondary">Live obs</span>
                    <p
                      class="font-medium text-ink-strong"
                      :class="{ 'line-through text-ink-disabled': entry.hasBeenSuperseded }"
                    >
                      {{ entry.liveObservationCount }}
                    </p>
                  </div>
                  <div v-if="entry.supersededObservationCount > 0">
                    <span class="text-ink-secondary">Superseded obs</span>
                    <p class="font-medium text-ink-disabled">
                      {{ entry.supersededObservationCount }}
                    </p>
                  </div>
                  <div v-if="entry.promotionEncounterId">
                    <span class="text-ink-secondary">Encounter</span>
                    <p class="font-mono text-xs text-ink-strong mt-0.5">
                      {{ entry.promotionEncounterId.substring(0, 8) }}…
                    </p>
                  </div>
                </div>

                <!-- Attribution (names from payload only) -->
                <dl class="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-2 text-sm border-t border-line pt-3">
                  <div>
                    <dt class="text-xs text-ink-secondary">Created</dt>
                    <dd class="text-ink">{{ formatDateTime(entry.createdAt) }}</dd>
                  </div>
                  <div v-if="entry.promotedAt">
                    <dt class="text-xs text-ink-secondary">Promoted</dt>
                    <dd class="text-ink">{{ formatDateTime(entry.promotedAt) }}</dd>
                  </div>
                  <div v-if="entry.enteredByUserName">
                    <dt class="text-xs text-ink-secondary">Entered by</dt>
                    <dd class="text-ink-strong">{{ entry.enteredByUserName }}</dd>
                  </div>
                  <div v-if="entry.verifiedByUserName">
                    <dt class="text-xs text-ink-secondary">Verified by</dt>
                    <dd class="text-ink-strong">{{ entry.verifiedByUserName }}</dd>
                  </div>
                  <div v-if="entry.approvedByUserName">
                    <dt class="text-xs text-ink-secondary">Approved / promoted by</dt>
                    <dd class="text-ink-strong">{{ entry.approvedByUserName }}</dd>
                  </div>
                </dl>

                <!-- Audit trail -->
                <details
                  v-if="entry.auditTrail.length > 0"
                  class="mt-4 group"
                >
                  <summary
                    class="text-sm font-medium text-primary-700 cursor-pointer hover:text-primary-800 list-none flex items-center gap-2"
                  >
                    <span
                      class="inline-flex h-5 w-5 items-center justify-center rounded border border-line text-xs text-ink-secondary group-open:rotate-90 transition-transform"
                      aria-hidden="true"
                    >
                      ›
                    </span>
                    Audit trail ({{ entry.auditTrail.length }} events)
                  </summary>

                  <div class="mt-3 overflow-x-auto">
                    <table class="w-full min-w-[480px] text-sm">
                      <thead>
                        <tr class="border-b border-line text-left text-ink-secondary">
                          <th class="py-2 px-2 font-medium w-[34%]">Timestamp</th>
                          <th class="py-2 px-2 font-medium">Event</th>
                          <th class="py-2 px-2 font-medium w-[28%]">Actor</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr
                          v-for="(event, idx) in entry.auditTrail"
                          :key="idx"
                          class="border-b border-line last:border-0"
                        >
                          <td class="py-2 px-2 text-ink-secondary whitespace-nowrap">
                            {{ formatDateTime(event.occurredAt) }}
                          </td>
                          <td class="py-2 px-2">
                            <span class="font-medium text-ink-strong">
                              {{ formatEventType(event.eventType) }}
                            </span>
                          </td>
                          <td class="py-2 px-2 text-ink">
                            {{ event.actorName || '—' }}
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </details>

                <!-- Create Correction -->
                <div
                  v-if="entry.status === 'PROMOTED' && !entry.hasBeenSuperseded"
                  class="mt-4 pt-3 border-t border-line"
                >
                  <button
                    type="button"
                    class="text-sm font-semibold text-primary-700 hover:text-primary-800"
                    @click="createCorrection(entry)"
                  >
                    Create Correction
                  </button>
                </div>
              </article>
            </div>
          </template>
        </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 StatusBadge from '../components/StatusBadge.vue'
import EmptyState from '../components/EmptyState.vue'
import SkeletonBlock from '../components/SkeletonBlock.vue'
import InlineError from '../components/InlineError.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)

async function reloadHistory() {
  if (!patientId.value) return
  history.value = await batchStore.getPatientHistory(patientId.value)
}

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

function formatBatchType(type: string): string {
  return type.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 formatDateTime(value: string): string {
  return new Date(value).toLocaleString()
}

function timelineAccentClass(entry: DigitizationHistoryEntry): string {
  if (entry.hasBeenSuperseded) return 'border-l-[3px] border-l-line-strong'
  if (entry.status === 'PROMOTED') return 'border-l-[3px] border-l-clinical-safe'
  if (entry.isCorrection) return 'border-l-[3px] border-l-primary-500'
  if (!['PROMOTED', 'CANCELLED'].includes(entry.status)) {
    return 'border-l-[3px] border-l-clinical-warning'
  }
  return ''
}

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>
