<template>
  <div
    v-if="show"
    class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-4"
  >
    <div class="bg-white rounded-lg p-6 max-w-md w-full">
      <h3 class="text-lg font-semibold mb-4">Assign Entry Clerk</h3>

      <p v-if="loading" class="text-sm text-gray-500 mb-4">Loading clerks...</p>
      <div v-else class="mb-4">
        <label class="block text-sm font-medium text-gray-700 mb-2">Entry Clerk</label>
        <select v-model="selectedClerkId" class="form-input">
          <option value="">Select entry clerk...</option>
          <option v-for="clerk in clerks" :key="clerk.id" :value="clerk.id">
            {{ clerk.fullName }} ({{ clerk.username }})
          </option>
        </select>
      </div>

      <div v-if="errorMessage" class="text-clinical-danger text-sm mb-4">
        {{ errorMessage }}
      </div>

      <div class="flex flex-col-reverse sm:flex-row sm:justify-end gap-4">
        <button
          type="button"
          @click="emit('close')"
          class="px-4 py-2 text-gray-600 hover:text-gray-800"
        >
          Cancel
        </button>
        <button
          type="button"
          @click="confirm"
          class="btn-primary"
          :disabled="!selectedClerkId || loading"
        >
          Assign Batch
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { get } from '../api/client'
import type { UserSummary } from '../types'

const props = defineProps<{
  show: boolean
  batchId: string | null
}>()

const emit = defineEmits<{
  close: []
  assigned: [batchId: string, clerkUserId: string]
}>()

const clerks = ref<UserSummary[]>([])
const selectedClerkId = ref('')
const loading = ref(false)
const errorMessage = ref('')

watch(
  () => props.show,
  async (visible) => {
    if (!visible) return

    selectedClerkId.value = ''
    errorMessage.value = ''
    loading.value = true

    try {
      const response = await get<UserSummary[]>('users', { role: 'DATA_ENTRY_CLERK' })
      if (response.success && response.data) {
        clerks.value = response.data
      } else {
        clerks.value = []
        errorMessage.value = response.error?.message ?? 'Failed to load entry clerks'
      }
    } catch (e: unknown) {
      clerks.value = []
      errorMessage.value = e instanceof Error ? e.message : 'Failed to load entry clerks'
    } finally {
      loading.value = false
    }
  }
)

function confirm(): void {
  if (!props.batchId || !selectedClerkId.value) return
  emit('assigned', props.batchId, selectedClerkId.value)
}
</script>
