<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import PatientRow from './PatientRow.vue'
import PatientCard from './PatientCard.vue'
import SortableHeader from './SortableHeader.vue'

defineProps({
  patients: { type: Array, required: true },
  sortField: { type: String, required: true },
  sortDirection: { type: String, required: true },
})

const emit = defineEmits(['sort'])
const router = useRouter()
const focusedRowIndex = ref(-1)

function goToPatient(encounterId) {
  router.push({ name: 'PatientDetail', params: { encounterId } })
}

function onTableKeydown(event) {
  if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return

  event.preventDefault()
  const rows = [...event.currentTarget.querySelectorAll('tr[data-patient-row]')]
  if (!rows.length) return

  let nextIndex = focusedRowIndex.value

  if (event.key === 'Home') nextIndex = 0
  else if (event.key === 'End') nextIndex = rows.length - 1
  else if (event.key === 'ArrowDown') nextIndex = Math.min(rows.length - 1, nextIndex + 1)
  else if (event.key === 'ArrowUp') nextIndex = Math.max(0, nextIndex - 1)

  if (nextIndex < 0) nextIndex = 0
  focusedRowIndex.value = nextIndex
  rows[nextIndex]?.focus()
}

function onRowFocus(index) {
  focusedRowIndex.value = index
}
</script>

<template>
  <!-- Mobile: card list -->
  <div class="space-y-4 md:hidden" role="list" aria-label="Ward patients">
    <PatientCard
      v-for="patient in patients"
      :key="patient.encounterId"
      :patient="patient"
      @activate="goToPatient(patient.encounterId)"
    />
  </div>

  <!-- Desktop: scrollable table -->
  <div class="hidden overflow-x-auto rounded-lg border border-gray-200 md:block dark:border-gray-700">
    <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700" aria-label="Ward patients">
      <thead class="sticky top-0 bg-gray-50 dark:bg-gray-800">
        <tr>
          <SortableHeader
            label="Room"
            field="roomBed"
            :active-field="sortField"
            :direction="sortDirection"
            @sort="emit('sort', $event)"
          />
          <SortableHeader
            label="Patient"
            field="name"
            :active-field="sortField"
            :direction="sortDirection"
            @sort="emit('sort', $event)"
          />
          <SortableHeader
            label="Department"
            field="department"
            :active-field="sortField"
            :direction="sortDirection"
            @sort="emit('sort', $event)"
          />
          <SortableHeader
            label="NEWS2"
            field="news2Score"
            :active-field="sortField"
            :direction="sortDirection"
            align="right"
            @sort="emit('sort', $event)"
          />
          <th scope="col" class="px-4 py-4 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
            SOFA
          </th>
          <th scope="col" class="px-4 py-4 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
            GCS
          </th>
          <SortableHeader
            label="qSOFA"
            field="qsofaScore"
            :active-field="sortField"
            :direction="sortDirection"
            align="right"
            @sort="emit('sort', $event)"
          />
          <th scope="col" class="px-4 py-4 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
            Attending
          </th>
          <th scope="col" class="px-4 py-4 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
            LOS
          </th>
          <th scope="col" class="px-4 py-4 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
            Last vitals
          </th>
          <SortableHeader
            label="Sepsis"
            field="sepsis"
            :active-field="sortField"
            :direction="sortDirection"
            @sort="emit('sort', $event)"
          />
          <SortableHeader
            label="Alerts"
            field="openAlertCount"
            :active-field="sortField"
            :direction="sortDirection"
            @sort="emit('sort', $event)"
          />
        </tr>
      </thead>
      <tbody
        class="divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-900"
        @keydown="onTableKeydown"
      >
        <PatientRow
          v-for="(patient, index) in patients"
          :key="patient.encounterId"
          :patient="patient"
          :tabindex="focusedRowIndex === index || (focusedRowIndex < 0 && index === 0) ? 0 : -1"
          class="cursor-pointer transition duration-200 hover:bg-gray-50 focus-visible:bg-gray-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-blue-500 dark:hover:bg-gray-800 dark:focus-visible:bg-gray-800"
          @focus="onRowFocus(index)"
          @activate="goToPatient(patient.encounterId)"
        />
      </tbody>
    </table>
  </div>
</template>
