<script setup>
import { computed } from 'vue'
import Card from '@/components/ui/Card.vue'
import Button from '@/components/ui/Button.vue'

const props = defineProps({
  session: { type: Object, required: true },
  activeRunCount: { type: Number, default: 0 },
  maxConcurrentRuns: { type: Number, default: 0 },
  starting: { type: Boolean, default: false },
})

const emit = defineEmits(['start'])

const scenarioCount = computed(() => props.session.scenarios?.length ?? 0)

const summaryLabel = computed(() => {
  const minutes = props.session.estimatedMinutes
  const patients = scenarioCount.value
  const timePart = minutes != null ? `~${minutes} min` : null
  const patientPart = `${patients} patient${patients === 1 ? '' : 's'}`
  return [timePart, patientPart].filter(Boolean).join(' · ')
})

const scenarioNames = computed(() =>
  (props.session.scenarios ?? []).map(s => s.name || s.id),
)

const insufficientCapacity = computed(() => {
  const max = props.maxConcurrentRuns
  if (!max) return false
  return props.activeRunCount + scenarioCount.value > max
})

const startDisabled = computed(() =>
  props.starting || insufficientCapacity.value || scenarioCount.value === 0,
)

const disabledReason = computed(() => {
  if (insufficientCapacity.value) {
    const need = scenarioCount.value
    const free = Math.max(0, props.maxConcurrentRuns - props.activeRunCount)
    return `Needs ${need} run slot${need === 1 ? '' : 's'} but only ${free} available (max ${props.maxConcurrentRuns}). Stop active runs or reset the ward first.`
  }
  return undefined
})

function onStart() {
  if (startDisabled.value) return
  emit('start', props.session.id)
}
</script>

<template>
  <Card padding="md" class="flex h-full flex-col transition hover:border-gray-300 dark:hover:border-gray-600">
    <h3 class="text-base font-semibold text-gray-900 dark:text-white">
      {{ session.name }}
    </h3>

    <p
      v-if="session.goal"
      class="mt-2 text-sm text-gray-600 dark:text-gray-400"
    >
      {{ session.goal }}
    </p>

    <p class="mt-3 text-xs font-medium text-gray-500 dark:text-gray-400">
      {{ summaryLabel }}
    </p>

    <ul
      v-if="scenarioNames.length"
      class="mt-3 list-inside list-disc space-y-1 text-sm text-gray-700 dark:text-gray-300"
    >
      <li v-for="name in scenarioNames" :key="name">{{ name }}</li>
    </ul>

    <div class="mt-4 border-t border-gray-100 pt-4 dark:border-gray-800">
      <Button
        class="w-full"
        size="sm"
        :disabled="startDisabled"
        :title="disabledReason"
        @click="onStart"
      >
        Start session
      </Button>
    </div>
  </Card>
</template>
