<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-ink-secondary">
          Batch: {{ currentBatch.id.substring(0, 8) }}...
          | Type: {{ currentBatch.batchType.replace(/_/g, ' ') }}
        </span>
      </template>
    </AppHeader>

    <WorkstationLayout :has-batch="!!batchId">
      <template #queue>
        <h2 class="text-xl font-semibold mb-4 text-ink-strong">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"
        />
      </template>

      <template #rail>
        <WorkstationQueueRail
          title="Entry queue"
          :batches="batchStore.batches"
          :selected-id="batchId"
          :loading="batchStore.loading"
          @select="openBatch"
          @back="router.push('/entry')"
        />
      </template>

      <template #scan>
        <ScanViewer
          :url="documentUrl"
          :loading="documentLoading"
          :error="documentError"
          @retry="refreshUrl"
        />
      </template>

      <template #form>
        <EntryForm
          v-if="batchId"
          :batch="currentBatch"
          :batch-id="batchId"
          :next-batch-id="nextBatchId"
          @open-next="openBatch"
        />
      </template>
    </WorkstationLayout>
  </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'
import WorkstationLayout from '../components/WorkstationLayout.vue'
import WorkstationQueueRail from '../components/WorkstationQueueRail.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, documentLoading, refreshUrl } = usePresignedUrl(batchId)

/** Next item in the loaded entry queue after the open batch (optional action-bar nav). */
const nextBatchId = computed(() => {
  const id = batchId.value
  if (!id) return undefined
  const list = batchStore.batches
  const idx = list.findIndex((b) => b.id === id)
  if (idx < 0 || idx >= list.length - 1) return undefined
  return list[idx + 1]?.id
})

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 () => {
  await loadQueue()
})
</script>
