<script setup>
import { ref } from 'vue'
import { RouterLink } from 'vue-router'
import Card from '@/components/ui/Card.vue'
import Badge from '@/components/ui/Badge.vue'
import Button from '@/components/ui/Button.vue'
import {
  formatSimClock,
  formatElapsedReal,
  formatSpeedBadge,
  runStatusLabel,
  runStatusVariant,
} from '@/composables/simulationFormat'

defineProps({
  activeRuns: { type: Array, default: () => [] },
  recentRuns: { type: Array, default: () => [] },
  stoppingId: { type: [String, null], default: null },
})

const emit = defineEmits(['stop'])

const confirmStopId = ref(null)

function requestStop(runId) {
  confirmStopId.value = runId
}

function cancelStop() {
  confirmStopId.value = null
}

function confirmStop(runId) {
  confirmStopId.value = null
  emit('stop', runId)
}

function patientLink(run) {
  return run.encounterId ? `/patients/${run.encounterId}` : null
}

function progressWidth(run) {
  const pct = Math.min(100, Math.max(0, Number(run.progressPercent) || 0))
  return `${pct}%`
}
</script>

<template>
  <div class="space-y-6">
    <div v-if="activeRuns.length" class="space-y-4">
      <h2 class="text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
        Active runs
      </h2>

      <Card
        v-for="run in activeRuns"
        :key="run.runId"
        padding="md"
      >
        <div class="flex flex-wrap items-start justify-between gap-4">
          <div class="min-w-0 flex-1">
            <div class="flex flex-wrap items-center gap-2">
              <h3 class="text-base font-semibold text-gray-900 dark:text-white">
                {{ run.scenarioName }}
              </h3>
              <Badge :variant="runStatusVariant(run.status)" size="xs">
                {{ runStatusLabel(run.status) }}
              </Badge>
              <span
                class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/30 dark:text-blue-300"
              >
                {{ formatSpeedBadge(run.speed) }}
              </span>
            </div>

            <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
              <template v-if="patientLink(run)">
                <RouterLink
                  :to="patientLink(run)"
                  class="font-medium text-blue-600 hover:underline dark:text-blue-400"
                >
                  {{ run.patientDisplayName || 'Open patient' }}
                </RouterLink>
              </template>
              <template v-else>
                {{ run.patientDisplayName || 'Patient pending…' }}
              </template>
            </p>
          </div>

          <div class="shrink-0">
            <template v-if="confirmStopId === run.runId">
              <div class="flex flex-col items-end gap-2">
                <p class="max-w-xs text-right text-xs text-gray-500 dark:text-gray-400">
                  Stopping leaves the patient on the ward.
                </p>
                <div class="flex gap-2">
                  <Button size="sm" variant="secondary" @click="cancelStop">
                    Cancel
                  </Button>
                  <Button
                    size="sm"
                    variant="danger"
                    :disabled="stoppingId === run.runId"
                    @click="confirmStop(run.runId)"
                  >
                    Confirm stop
                  </Button>
                </div>
              </div>
            </template>
            <Button
              v-else
              size="sm"
              variant="danger"
              :disabled="run._optimistic || stoppingId === run.runId"
              @click="requestStop(run.runId)"
            >
              Stop
            </Button>
          </div>
        </div>

        <div class="mt-4">
          <div class="mb-1 flex justify-between text-xs text-gray-500 dark:text-gray-400">
            <span>{{ formatSimClock(run.lastOffsetMinutes, run.totalOffsetMinutes) }}</span>
            <span>{{ Math.round(run.progressPercent ?? 0) }}%</span>
          </div>
          <div
            class="h-2 overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800"
            role="progressbar"
            :aria-valuenow="Math.round(run.progressPercent ?? 0)"
            aria-valuemin="0"
            aria-valuemax="100"
          >
            <div
              class="h-full rounded-full bg-blue-600 transition-all dark:bg-blue-500"
              :style="{ width: progressWidth(run) }"
            />
          </div>
          <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
            Wall clock {{ formatElapsedReal(run.elapsedRealSeconds) }}
          </p>
        </div>

        <dl class="mt-4 grid grid-cols-3 gap-4 text-sm">
          <div>
            <dt class="text-gray-500 dark:text-gray-400">Observations</dt>
            <dd class="mt-0.5 font-semibold text-gray-900 dark:text-white">
              {{ run.observationsSent ?? 0 }}
            </dd>
          </div>
          <div>
            <dt class="text-gray-500 dark:text-gray-400">Medications</dt>
            <dd class="mt-0.5 font-semibold text-gray-900 dark:text-white">
              {{ run.medicationsSent ?? 0 }}
            </dd>
          </div>
          <div>
            <dt class="text-gray-500 dark:text-gray-400">Orders</dt>
            <dd class="mt-0.5 font-semibold text-gray-900 dark:text-white">
              {{ run.ordersPlaced ?? 0 }}
            </dd>
          </div>
        </dl>

        <p
          v-if="run.status === 'FAILED' && run.failureReason"
          class="mt-4 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-300"
          role="alert"
        >
          {{ run.failureReason }}
        </p>
      </Card>
    </div>

    <div v-if="recentRuns.length">
      <h2 class="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
        Recent runs
      </h2>
      <div class="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
        <table class="min-w-full divide-y divide-gray-200 text-sm dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-900">
            <tr>
              <th class="px-4 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Scenario</th>
              <th class="px-4 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Status</th>
              <th class="px-4 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Duration</th>
              <th class="px-4 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Counters</th>
              <th class="px-4 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Patient</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-900">
            <tr
              v-for="run in recentRuns"
              :key="run.runId"
              :class="run.status === 'FAILED' ? 'bg-red-50/50 dark:bg-red-950/20' : ''"
            >
              <td class="px-4 py-3 text-gray-900 dark:text-white">
                {{ run.scenarioName }}
                <p
                  v-if="run.status === 'FAILED' && run.failureReason"
                  class="mt-1 text-xs text-red-600 dark:text-red-400"
                >
                  {{ run.failureReason }}
                </p>
              </td>
              <td class="px-4 py-3">
                <Badge :variant="runStatusVariant(run.status)" size="xs">
                  {{ runStatusLabel(run.status) }}
                </Badge>
              </td>
              <td class="whitespace-nowrap px-4 py-3 text-gray-600 dark:text-gray-400">
                {{ formatElapsedReal(run.elapsedRealSeconds) }}
                <span class="text-gray-400">·</span>
                {{ formatSpeedBadge(run.speed) }}
              </td>
              <td class="whitespace-nowrap px-4 py-3 text-gray-600 dark:text-gray-400">
                {{ run.observationsSent ?? 0 }} obs ·
                {{ run.medicationsSent ?? 0 }} med ·
                {{ run.ordersPlaced ?? 0 }} ord
              </td>
              <td class="px-4 py-3">
                <RouterLink
                  v-if="patientLink(run)"
                  :to="patientLink(run)"
                  class="font-medium text-blue-600 hover:underline dark:text-blue-400"
                >
                  {{ run.patientDisplayName || 'Open' }}
                </RouterLink>
                <span v-else class="text-gray-400">—</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>
