<template>
  <div class="h-full min-h-0 flex flex-col">
    <AppHeader title="Data Entry">
      <template #subtitle>
        <span v-if="currentBatch" class="text-sm text-gray-500">
          Batch: {{ currentBatch.id.substring(0, 8) }}...
          | Type: {{ currentBatch.batchType.replace(/_/g, ' ') }}
        </span>
      </template>
    </AppHeader>

    <!-- Queue view (no batch selected) -->
    <div v-if="!batchId" class="flex-1 p-4 sm:p-6">
      <h2 class="text-xl font-semibold mb-4">Data Entry Queue</h2>
      <BatchList
        :batches="batchStore.batches"
        :loading="batchStore.loading"
        :error="batchStore.error"
        empty-title="No batches are assigned for data entry."
        empty-description="Assigned batches appear here after intake assigns them to you."
        @select="openBatch"
        @retry="loadQueue"
      />
    </div>

    <!-- Split pane (batch selected) -->
    <div v-else class="flex-1 split-pane">
      <ScanViewer
        v-if="documentUrl"
        :url="documentUrl"
      />
      <div v-else class="flex items-center justify-center bg-gray-100 rounded-lg">
        <p class="text-gray-500">{{ documentError ?? 'Loading document...' }}</p>
      </div>

      <EntryForm
        :batch="currentBatch"
        :batch-id="batchId"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useBatchStore } from '../stores/batches'
import { usePresignedUrl } from '../composables/usePresignedUrl'
import AppHeader from '../components/AppHeader.vue'
import ScanViewer from '../components/ScanViewer.vue'
import EntryForm from '../components/EntryForm.vue'
import BatchList from '../components/BatchList.vue'

const props = defineProps<{ batchId?: string }>()

const auth = useAuthStore()
const batchStore = useBatchStore()
const route = useRoute()
const router = useRouter()

const batchId = computed(() => props.batchId ?? (route.params.batchId as string | undefined))
const currentBatch = computed(() => batchStore.currentBatch)
const { documentUrl, documentError } = usePresignedUrl(batchId)

async function openBatch(id: string) {
  router.push(`/entry/${id}`)
}

async function loadQueue() {
  await batchStore.listBatches({
    assignedTo: auth.userId,
    page: 1,
    pageSize: 50,
  })
}

watch(
  batchId,
  async (id) => {
    if (id) {
      await batchStore.getDraft(id)
    }
  },
  { immediate: true }
)

onMounted(async () => {
  if (!batchId.value) {
    await loadQueue()
  }
})
</script>
