<script setup>
import { ref, onMounted } from 'vue'
import Button from '@/components/ui/Button.vue'
import Skeleton from '@/components/ui/Skeleton.vue'
import { buildHandoffReport, formatReportTimestamp } from '@/composables/handoffReport'

const props = defineProps({
  encounters: { type: Array, required: true },
  department: { type: String, default: null },
  generatedBy: { type: String, default: 'Clinical user' },
})

const emit = defineEmits(['close'])

const loading = ref(true)
const error = ref('')
const report = ref(null)

onMounted(async () => {
  try {
    report.value = await buildHandoffReport(
      props.encounters,
      props.department,
      props.generatedBy,
    )
  } catch (err) {
    error.value = err.message ?? 'Failed to generate handoff report'
  } finally {
    loading.value = false
  }
})

function printReport() {
  window.print()
}
</script>

<template>
  <Teleport to="body">
    <div class="handoff-root fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/50 p-4 print:relative print:inset-auto print:block print:overflow-visible print:bg-white print:p-0">
    <div class="handoff-panel my-4 w-full max-w-5xl rounded-lg border border-gray-200 bg-white shadow-xl print:my-0 print:max-w-none print:rounded-none print:border-0 print:shadow-none dark:border-gray-700 dark:bg-gray-900 print:dark:bg-white">
      <div class="handoff-controls flex flex-wrap items-center justify-between gap-3 border-b border-gray-200 px-4 py-3 dark:border-gray-700">
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Shift Handoff Report</h2>
        <div class="flex flex-wrap gap-2">
          <Button size="sm" variant="secondary" @click="printReport">
            Print / Save PDF
          </Button>
          <Button size="sm" variant="ghost" @click="emit('close')">
            Close
          </Button>
        </div>
      </div>

      <div class="handoff-body p-4 text-gray-900 print:p-8 dark:text-gray-100 print:dark:text-gray-900">
        <Skeleton v-if="loading" :rows="8" />
        <p v-else-if="error" class="text-sm text-red-600">{{ error }}</p>

        <div v-else-if="report" class="handoff-print-area space-y-6">
          <header class="border-b border-gray-300 pb-4">
            <h1 class="text-2xl font-bold">Shift Handoff Report</h1>
            <p class="mt-1 text-sm text-gray-600">
              {{ report.summary.department }} · Generated {{ formatReportTimestamp(report.generatedAt) }}
            </p>
            <p v-if="report.generatedBy" class="text-sm text-gray-600">
              Prepared by {{ report.generatedBy }}
            </p>
          </header>

          <section>
            <h2 class="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-600">Ward Summary</h2>
            <div class="grid grid-cols-2 gap-3 text-sm sm:grid-cols-4">
              <div class="rounded border border-gray-200 p-3 print:border-gray-400">
                <div class="text-xs uppercase text-gray-500">Patients</div>
                <div class="text-xl font-semibold">{{ report.summary.patientCount }}</div>
              </div>
              <div class="rounded border border-gray-200 p-3 print:border-gray-400">
                <div class="text-xs uppercase text-gray-500">Critical (NEWS2 ≥ 7)</div>
                <div class="text-xl font-semibold">{{ report.summary.criticalCount }}</div>
              </div>
              <div class="rounded border border-gray-200 p-3 print:border-gray-400">
                <div class="text-xs uppercase text-gray-500">Open Alerts</div>
                <div class="text-xl font-semibold">{{ report.summary.alertCount }}</div>
              </div>
              <div class="rounded border border-gray-200 p-3 print:border-gray-400">
                <div class="text-xs uppercase text-gray-500">Active Bundles</div>
                <div class="text-xl font-semibold">{{ report.summary.activeBundles }}</div>
              </div>
            </div>
          </section>

          <section
            v-for="patient in report.patients"
            :key="patient.encounterId"
            class="break-inside-avoid border-t border-gray-300 pt-4"
          >
            <div class="mb-3 flex flex-wrap items-baseline justify-between gap-2">
              <h3 class="text-lg font-semibold">{{ patient.name }}</h3>
              <span class="text-sm text-gray-600">
                MRN {{ patient.mrn }} · Room {{ patient.room }} · {{ patient.department }}
              </span>
            </div>

            <table class="mb-4 w-full border-collapse text-sm">
              <thead>
                <tr class="border-b border-gray-300 text-left text-xs uppercase text-gray-500">
                  <th class="py-1 pr-3">NEWS2</th>
                  <th class="py-1 pr-3">SOFA</th>
                  <th class="py-1 pr-3">GCS</th>
                  <th class="py-1 pr-3">qSOFA</th>
                  <th class="py-1 pr-3">Attending</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td class="py-1 pr-3 font-medium">{{ patient.news2 ?? '—' }}</td>
                  <td class="py-1 pr-3 font-medium">
                    {{ patient.sofa ?? '—' }}
                    <span v-if="patient.sofaDelta"> (Δ+{{ patient.sofaDelta }})</span>
                  </td>
                  <td class="py-1 pr-3 font-medium">{{ patient.gcs ?? '—' }}</td>
                  <td class="py-1 pr-3 font-medium">{{ patient.qsofa ?? '—' }}</td>
                  <td class="py-1 pr-3">{{ patient.attending }}</td>
                </tr>
              </tbody>
            </table>

            <dl class="mb-4 grid gap-2 text-sm sm:grid-cols-2">
              <div>
                <dt class="text-xs font-medium uppercase text-gray-500">Key Vitals</dt>
                <dd>{{ patient.vitalsSummary }}</dd>
              </div>
              <div>
                <dt class="text-xs font-medium uppercase text-gray-500">Active Alerts</dt>
                <dd>{{ patient.alertsSummary }}</dd>
              </div>
              <div class="sm:col-span-2">
                <dt class="text-xs font-medium uppercase text-gray-500">Pending Orders</dt>
                <dd>{{ patient.pendingOrders }}</dd>
              </div>
            </dl>

            <div class="rounded border border-gray-200 p-3 text-sm print:border-gray-400">
              <h4 class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">SBAR</h4>
              <dl class="space-y-2">
                <div>
                  <dt class="font-medium">Situation</dt>
                  <dd class="text-gray-700">{{ patient.sbar.situation }}</dd>
                </div>
                <div>
                  <dt class="font-medium">Background</dt>
                  <dd class="text-gray-700">{{ patient.sbar.background }}</dd>
                </div>
                <div>
                  <dt class="font-medium">Assessment</dt>
                  <dd class="text-gray-700">{{ patient.sbar.assessment }}</dd>
                </div>
                <div>
                  <dt class="font-medium">Recommendation</dt>
                  <dd class="text-gray-700">{{ patient.sbar.recommendation }}</dd>
                </div>
              </dl>
            </div>
          </section>
        </div>
      </div>
    </div>
    </div>
  </Teleport>
</template>

<style>
@media print {
  body > *:not(.handoff-root) {
    display: none !important;
  }

  .handoff-root {
    position: static !important;
    overflow: visible !important;
    background: white !important;
    padding: 0 !important;
  }

  .handoff-controls {
    display: none !important;
  }

  .handoff-panel {
    box-shadow: none !important;
    border: none !important;
    max-width: none !important;
    margin: 0 !important;
  }

  .handoff-body {
    padding: 0 !important;
  }
}
</style>
