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

const props = defineProps({
  summary: {
    type: Object,
    default: () => ({
      simulatedPatients: 0,
      encounters: 0,
      observations: 0,
      alerts: 0,
      activeRuns: 0,
    }),
  },
  purging: { type: Boolean, default: false },
  stoppingAll: { type: Boolean, default: false },
})

const emit = defineEmits(['purge', 'stop-all'])

const confirmOpen = ref(false)
const confirmText = ref('')

const hasActiveRuns = computed(() => (props.summary?.activeRuns ?? 0) > 0)
const patientCount = computed(() => props.summary?.simulatedPatients ?? 0)
const observationCount = computed(() => props.summary?.observations ?? 0)
const alertCount = computed(() => props.summary?.alerts ?? 0)

const countsSentence = computed(() => {
  const patients = patientCount.value
  const observations = observationCount.value
  const alerts = alertCount.value
  return [
    `${patients} simulated patient${patients === 1 ? '' : 's'}`,
    `${observations} observation${observations === 1 ? '' : 's'}`,
    `${alerts} alert${alerts === 1 ? '' : 's'}`,
  ].join(', ')
})

const confirmEnabled = computed(() =>
  confirmText.value.trim().toUpperCase() === 'RESET' && !props.purging,
)

watch(confirmOpen, (open) => {
  if (open) confirmText.value = ''
})

function openConfirm() {
  if (hasActiveRuns.value) return
  confirmOpen.value = true
}

function closeConfirm() {
  confirmOpen.value = false
  confirmText.value = ''
}

function onConfirm() {
  if (!confirmEnabled.value) return
  emit('purge')
}

function onStopAll() {
  emit('stop-all')
}

defineExpose({ closeConfirm })
</script>

<template>
  <Card padding="md">
    <div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
      <div>
        <h2 class="text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
          Reset ward
        </h2>
        <p class="mt-2 text-sm text-gray-700 dark:text-gray-300">
          <template v-if="patientCount > 0">
            {{ patientCount }} simulated patient{{ patientCount === 1 ? '' : 's' }}
            currently on the ward
            <span class="text-gray-500 dark:text-gray-400">
              ({{ observationCount }} observations, {{ alertCount }} alerts).
            </span>
          </template>
          <template v-else>
            No simulated patients on the ward.
          </template>
        </p>
        <p
          v-if="hasActiveRuns"
          class="mt-2 text-sm text-amber-800 dark:text-amber-200"
          role="status"
        >
          Reset is blocked while {{ summary.activeRuns }} run{{ summary.activeRuns === 1 ? '' : 's' }}
          {{ summary.activeRuns === 1 ? 'is' : 'are' }} still active. Stop them first.
        </p>
      </div>

      <div class="flex flex-wrap gap-2">
        <Button
          v-if="hasActiveRuns"
          variant="secondary"
          size="sm"
          :disabled="stoppingAll"
          @click="onStopAll"
        >
          {{ stoppingAll ? 'Stopping…' : 'Stop all runs' }}
        </Button>
        <Button
          variant="danger"
          size="sm"
          :disabled="hasActiveRuns || purging || patientCount === 0"
          :title="hasActiveRuns
            ? 'Stop all active runs before resetting the ward.'
            : patientCount === 0
              ? 'Nothing to reset.'
              : undefined"
          @click="openConfirm"
        >
          Reset ward
        </Button>
      </div>
    </div>

    <Modal
      :open="confirmOpen"
      title="Reset simulated ward"
      title-id="reset-ward-title"
      @close="closeConfirm"
    >
      <div class="space-y-4">
        <p class="text-sm text-gray-700 dark:text-gray-300">
          This will permanently delete
          <span class="font-medium text-gray-900 dark:text-white">{{ countsSentence }}</span>.
        </p>
        <p class="text-sm text-gray-700 dark:text-gray-300">
          Alert feedback for those patients is deleted with them. Non-simulated patients are not affected.
        </p>

        <label class="block">
          <span class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
            Type <kbd class="rounded bg-gray-100 px-1.5 py-0.5 font-mono text-xs dark:bg-gray-700">RESET</kbd>
            to confirm
          </span>
          <input
            v-model="confirmText"
            type="text"
            autocomplete="off"
            class="w-full rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm text-gray-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100"
            placeholder="RESET"
          >
        </label>

        <div class="flex justify-end gap-2">
          <Button variant="secondary" size="sm" :disabled="purging" @click="closeConfirm">
            Cancel
          </Button>
          <Button
            variant="danger"
            size="sm"
            :disabled="!confirmEnabled"
            @click="onConfirm"
          >
            {{ purging ? 'Resetting…' : 'Reset ward' }}
          </Button>
        </div>
      </div>
    </Modal>
  </Card>
</template>
