<template>
  <div class="compact-upload-zone">
    <div
      class="upload-strip"
      :class="{ 'dragging': isDragging, 'processing': processing, 'has-file': selectedFile }"
      @dragover.prevent="onDragOver"
      @dragleave.prevent="onDragLeave"
      @drop.prevent="onDrop"
      @click="triggerFileInput"
    >
      <input
        ref="fileInput"
        type="file"
        accept="image/*,application/pdf"
        class="hidden-input"
        @change="onFileSelected"
      />

      <!-- Processing state -->
      <div v-if="processing" class="strip-content processing-state">
        <ProgressSpinner style="width: 24px; height: 24px" strokeWidth="4" />
        <span class="processing-text">{{ processingMessage }}</span>
        <span class="processing-subtext" v-if="processingSubtext">{{ processingSubtext }}</span>
      </div>

      <!-- File selected state -->
      <div v-else-if="selectedFile" class="strip-content file-state">
        <i class="pi pi-check-circle" style="color: var(--green-500);"></i>
        <span class="file-name">{{ selectedFile.name }}</span>
        <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
      </div>

      <!-- Empty state -->
      <div v-else class="strip-content empty-state">
        <i class="pi pi-camera"></i>
        <span v-if="isDragging">Elibereaza pentru a incarca</span>
        <span v-else>Trage poza bonului aici sau click pentru a selecta</span>
      </div>
    </div>

    <!-- Action bar (inline with file strip) -->
    <div v-if="selectedFile && !processing" class="action-bar">
      <Button
        icon="pi pi-refresh"
        severity="secondary"
        size="small"
        @click.stop="triggerFileInput"
        v-tooltip.top="'Schimba fisier'"
      />
      <Dropdown
        v-model="selectedEngine"
        :options="engineOptions"
        optionLabel="label"
        optionValue="value"
        placeholder="OCR"
        class="engine-selector dropdown-borderless"
        @click.stop
      />
      <Button
        label="OCR"
        icon="pi pi-play"
        size="small"
        @click.stop="processOCR"
      />
    </div>

    <!-- Error message -->
    <Message v-if="error" severity="error" :closable="true" @close="error = null" class="error-message">
      {{ error }}
    </Message>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import Dropdown from 'primevue/dropdown'
import Message from 'primevue/message'
import ProgressSpinner from 'primevue/progressspinner'
import Button from 'primevue/button'
import api from '@data-entry/services/api'
import { useOCRSettingsStore } from '@data-entry/stores/ocrSettingsStore'

const emit = defineEmits(['ocr-result', 'file-selected', 'error'])

const fileInput = ref(null)
const selectedFile = ref(null)
const isDragging = ref(false)
const processing = ref(false)
const error = ref(null)

// OCR Settings Store
const ocrStore = useOCRSettingsStore()
const selectedEngine = ref('auto')

// Engine config
const engineConfig = {
  'auto': { label: 'Auto', desc: 'docTR→Paddle→Tess' },
  'doctr': { label: 'docTR', desc: 'Rapid, buna acuratete' },
  'doctr_plus': { label: 'docTR Plus', desc: '2 treceri (recomandat)' },
  'paddleocr': { label: 'PaddleOCR', desc: 'Cea mai buna calitate' },
  'tesseract': { label: 'Tesseract', desc: 'Cel mai rapid' },
  'hybrid': { label: 'Hybrid', desc: 'docTR+Tess paralel' },
  'hybrid-quality': { label: 'Hybrid Calitate', desc: 'Acuratete max' },
}

const engineOptions = computed(() => {
  return ocrStore.availableEngines.map(engine => ({
    label: engineConfig[engine]?.label || engine,
    desc: engineConfig[engine]?.desc || '',
    value: engine
  }))
})

// Job queue state
const jobId = ref(null)
const queuePosition = ref(null)
const estimatedWait = ref(null)
const jobStatus = ref(null)

const processingMessage = computed(() => {
  if (jobStatus.value === 'pending' && queuePosition.value > 0) {
    return `In coada (${queuePosition.value})`
  }
  if (jobStatus.value === 'processing') {
    return 'Se proceseaza...'
  }
  return 'Se trimite...'
})

const processingSubtext = computed(() => {
  if (jobStatus.value === 'pending' && estimatedWait.value > 0) {
    return `~${estimatedWait.value}s`
  }
  return ''
})

// Load user preference on mount
onMounted(async () => {
  await ocrStore.loadPreference()
  selectedEngine.value = ocrStore.preferredEngine
})

// Save preference when changed
watch(selectedEngine, async (newEngine, oldEngine) => {
  if (oldEngine && newEngine !== oldEngine && ocrStore.initialized) {
    try {
      await ocrStore.setPreference(newEngine)
    } catch (err) {
      console.error('[CompactUploadZone] Failed to save preference:', err)
    }
  }
})

const onDragOver = () => { isDragging.value = true }
const onDragLeave = () => { isDragging.value = false }

const onDrop = (event) => {
  isDragging.value = false
  const files = event.dataTransfer?.files
  if (files?.length > 0) handleFile(files[0])
}

const triggerFileInput = () => { fileInput.value?.click() }

const onFileSelected = (event) => {
  const files = event.target?.files
  if (files?.length > 0) handleFile(files[0])
}

const handleFile = async (file) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']
  if (!allowedTypes.includes(file.type)) {
    error.value = 'Tip de fisier invalid. Acceptate: JPG, PNG, PDF'
    return
  }
  if (file.size > 10 * 1024 * 1024) {
    error.value = 'Fisier prea mare. Max 10MB.'
    return
  }

  error.value = null

  // Clone file to avoid Android SnapshotState issue
  try {
    const arrayBuffer = await file.arrayBuffer()
    const clonedFile = new File([arrayBuffer], file.name, {
      type: file.type,
      lastModified: file.lastModified
    })
    selectedFile.value = clonedFile
    emit('file-selected', clonedFile)
  } catch (e) {
    console.warn('File clone failed:', e)
    selectedFile.value = file
    emit('file-selected', file)
  }
}

const processOCR = async () => {
  if (!selectedFile.value) return

  processing.value = true
  error.value = null
  jobId.value = null
  queuePosition.value = null
  estimatedWait.value = null
  jobStatus.value = 'submitting'

  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value)

    // Submit job
    const submitResponse = await api.post(`/ocr/extract?engine=${selectedEngine.value}`, formData, {
      timeout: 30000,
    })

    const job = submitResponse.data
    jobId.value = job.job_id
    queuePosition.value = job.queue_position
    estimatedWait.value = job.estimated_wait_seconds
    jobStatus.value = job.status

    // Poll for result
    await pollJobStatus(job.job_id)

  } catch (err) {
    const message = err.response?.data?.detail || err.message || 'Eroare OCR'
    error.value = message
    emit('error', message)
    processing.value = false
  }
}

const pollJobStatus = async (id) => {
  const LONG_POLL_TIMEOUT = 30
  const MAX_TOTAL_TIME = 120
  const MIN_POLL_INTERVAL = 500
  const startTime = Date.now()

  const poll = async () => {
    const elapsed = (Date.now() - startTime) / 1000
    if (elapsed >= MAX_TOTAL_TIME) {
      processing.value = false
      error.value = 'Timeout - procesare prea lunga'
      emit('error', error.value)
      return
    }

    const pollStartTime = Date.now()

    try {
      const response = await api.get(`/ocr/jobs/${id}/wait`, {
        params: { timeout: LONG_POLL_TIMEOUT, _t: Date.now() },
        timeout: (LONG_POLL_TIMEOUT + 5) * 1000,
        headers: { 'Cache-Control': 'no-cache' }
      })

      const job = response.data
      jobStatus.value = job.status
      queuePosition.value = job.queue_position
      estimatedWait.value = job.estimated_wait_seconds

      if (job.status === 'completed') {
        processing.value = false
        if (job.result) {
          emit('ocr-result', {
            ...job.result,
            _processing_time_ms: job.processing_time_ms
          })
        } else {
          error.value = 'OCR completat dar fara rezultat'
          emit('error', error.value)
        }
        return
      }

      if (job.status === 'failed') {
        processing.value = false
        error.value = job.error || 'Procesare OCR esuata'
        emit('error', error.value)
        return
      }

      // Still pending/processing
      if (processing.value) {
        const pollDuration = Date.now() - pollStartTime
        if (pollDuration < MIN_POLL_INTERVAL) {
          await new Promise(resolve => setTimeout(resolve, MIN_POLL_INTERVAL - pollDuration))
        }
        await poll()
      }

    } catch (err) {
      if (err.code === 'ECONNABORTED' || err.message?.includes('timeout')) {
        if (processing.value) await poll()
        return
      }

      const elapsed = (Date.now() - startTime) / 1000
      if (elapsed < MAX_TOTAL_TIME && processing.value) {
        await new Promise(resolve => setTimeout(resolve, MIN_POLL_INTERVAL))
        await poll()
        return
      }

      processing.value = false
      error.value = 'Eroare verificare job'
      emit('error', error.value)
    }
  }

  await poll()
}

const formatFileSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

const reset = () => {
  selectedFile.value = null
  error.value = null
  jobId.value = null
  queuePosition.value = null
  estimatedWait.value = null
  jobStatus.value = null
  processing.value = false
  if (fileInput.value) fileInput.value.value = ''
}

defineExpose({ reset, processOCR })
</script>

<style scoped>
.compact-upload-zone {
  margin-bottom: var(--space-xs);
}

.upload-strip {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 28px;
  padding: 2px var(--space-sm);  /* reduced vertical padding */
  border: 1px dashed var(--surface-border);
  border-radius: var(--radius-sm);
  background: var(--surface-ground);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.upload-strip:hover {
  border-color: var(--primary-500);
  background: var(--surface-hover);
}

.upload-strip.dragging {
  border-color: var(--primary-500);
  background: var(--primary-50);
}

.upload-strip.processing {
  cursor: default;
  background: var(--surface-card);
}

.upload-strip.has-file {
  border-style: solid;
  border-color: var(--green-300);
  background: var(--green-50);
}

.hidden-input {
  display: none;
}

.strip-content {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  font-size: var(--text-sm);  /* bigger - 0.875rem */
}

.strip-content i {
  font-size: var(--text-sm);
}

.empty-state {
  color: var(--text-color-secondary);
}

.empty-state i {
  color: var(--primary-500);
}

.file-state {
  color: var(--text-color);
}

.file-name {
  font-weight: var(--font-medium);
  max-width: 200px;  /* wider */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
}

.processing-state {
  color: var(--text-color-secondary);
}

.processing-text {
  font-weight: var(--font-medium);
}

.processing-subtext {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
}

/* Action bar - single line */
.action-bar {
  display: flex;
  flex-wrap: nowrap;
  gap: var(--space-sm);
  margin-top: 2px;  /* minimal margin */
  justify-content: center;
  align-items: center;
}

.action-bar :deep(.p-button) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-xs);
  height: 28px;
}

.action-bar :deep(.p-button .p-button-icon) {
  font-size: var(--text-sm);
}

.engine-selector {
  min-width: 100px;
}

.engine-selector :deep(.p-dropdown) {
  padding: 0 var(--space-xs);
  font-size: var(--text-xs);
  min-height: 28px;
  height: 28px;
}

.engine-selector :deep(.p-dropdown-label) {
  padding: var(--space-xs);
}

.engine-selector :deep(.p-dropdown-trigger) {
  width: 24px;
}

.engine-option {
  display: flex;
  flex-direction: column;
  gap: 0;
  padding: 2px 0;
}

.engine-label {
  font-weight: var(--font-medium);
  font-size: var(--text-xs);  /* 12px - uniform */
}

.engine-desc {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
}

.error-message {
  margin-top: var(--space-xs);
}

.error-message :deep(.p-message) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-xs);  /* 12px - uniform */
}

/* Responsive */
@media (max-width: 480px) {
  .strip-content span:not(.file-name) {
    display: none;
  }

  .strip-content .file-name {
    max-width: 150px;
  }

  .action-bar {
    gap: var(--space-xs);
  }

  .engine-selector {
    min-width: 90px;
  }
}
</style>
