<script setup>
import { ref, watch, onBeforeUnmount } from 'vue'
import Card from '@/components/ui/Card.vue'
import Button from '@/components/ui/Button.vue'
import Skeleton from '@/components/ui/Skeleton.vue'
import {
  fetchDischargeSummaryStatus,
  fetchDischargeSummaryContent,
} from '@/api/encounters'

const props = defineProps({
  encounterId: { type: String, required: true },
  discharged: { type: Boolean, default: false },
})

const loading = ref(true)
const error = ref('')
const status = ref(null)
const content = ref('')
let pollTimer = null

async function loadStatus() {
  if (!props.discharged) {
    loading.value = false
    return
  }

  error.value = ''
  try {
    status.value = await fetchDischargeSummaryStatus(props.encounterId)
    if (status.value?.status === 'Ready') {
      content.value = await fetchDischargeSummaryContent(props.encounterId)
      stopPolling()
    } else if (status.value?.status === 'Pending') {
      content.value = ''
      startPolling()
    }
  } catch (err) {
    error.value = err.message
    stopPolling()
  } finally {
    loading.value = false
  }
}

function startPolling() {
  stopPolling()
  pollTimer = setInterval(loadStatus, 5000)
}

function stopPolling() {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
}

function downloadSummary() {
  if (!content.value) return
  const blob = new Blob([content.value], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'discharge-summary.pdf'
  link.click()
  URL.revokeObjectURL(url)
}

function formatDischargedAt(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleString()
}

watch(() => [props.encounterId, props.discharged], () => {
  loading.value = true
  loadStatus()
}, { immediate: true })

onBeforeUnmount(stopPolling)
</script>

<template>
  <Card v-if="discharged">
    <template #header>
      <div class="mb-4 flex flex-wrap items-center justify-between gap-2">
        <h2 class="text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
          Discharge Summary
        </h2>
        <Button
          v-if="content"
          size="sm"
          variant="secondary"
          @click="downloadSummary"
        >
          Download
        </Button>
      </div>
    </template>

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

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

    <div v-else-if="status?.status === 'Pending'" class="space-y-2 text-sm text-gray-600 dark:text-gray-400">
      <p>Discharge summary is being generated…</p>
      <p v-if="status.dischargedAt">
        Discharged {{ formatDischargedAt(status.dischargedAt) }}
      </p>
    </div>

    <div v-else-if="status?.status === 'Ready'" class="space-y-3">
      <p class="text-xs text-gray-500 dark:text-gray-400">
        Generated document · Discharged {{ formatDischargedAt(status.dischargedAt) }}
      </p>
      <pre class="max-h-96 overflow-auto rounded-lg border border-gray-200 bg-gray-50 p-4 text-xs whitespace-pre-wrap text-gray-800 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100">{{ content }}</pre>
    </div>

    <p v-else class="text-sm text-gray-500 dark:text-gray-400">
      Discharge summary is not available for this encounter.
    </p>
  </Card>
</template>
