<template>
  <div class="ocr-preview">
    <div class="preview-header">
      <div class="header-left">
        <i class="pi pi-check-circle" style="color: var(--green-500); font-size: 1.25rem;"></i>
        <span class="title">Date extrase din imagine</span>
      </div>
      <div class="header-right">
        <span class="overall-confidence">
          <OCRConfidenceIndicator
            :confidence="data.overall_confidence"
            :show-percentage="true"
            size="normal"
          />
        </span>
        <Button
          icon="pi pi-minus"
          text
          rounded
          size="small"
          @click="$emit('collapse')"
          class="collapse-btn"
        />
      </div>
    </div>

    <div class="preview-content">
      <!-- SECTION: FURNIZOR -->
      <div class="ocr-section" v-if="data.partner_name || data.cui || data.address">
        <div class="ocr-section-title">FURNIZOR</div>
        <div class="ocr-section-content">
          <div class="vendor-name" v-if="data.partner_name">
            {{ data.partner_name }}
            <OCRConfidenceIndicator :confidence="data.confidence_vendor" size="small" />
          </div>
          <div class="vendor-cui" v-if="data.cui">CUI: {{ data.cui }}</div>
          <div class="vendor-address" v-if="data.address">{{ data.address }}</div>
        </div>
      </div>

      <!-- SECTION: CLIENT (always visible) -->
      <div class="ocr-section">
        <div class="ocr-section-title">CLIENT</div>
        <div class="ocr-section-content">
          <template v-if="data.client_name || data.client_cui || data.client_address">
            <div class="client-name" v-if="data.client_name">
              {{ data.client_name }}
              <OCRConfidenceIndicator v-if="data.confidence_client" :confidence="data.confidence_client" size="small" />
            </div>
            <div class="client-cui" v-if="data.client_cui">CUI: {{ data.client_cui }}</div>
            <div class="client-address" v-if="data.client_address">{{ data.client_address }}</div>
          </template>
          <div v-else class="no-data">-</div>
        </div>
      </div>

      <!-- SECTION: DOCUMENT -->
      <div class="ocr-section" v-if="data.receipt_type || data.receipt_number || data.receipt_date">
        <div class="ocr-section-title">DOCUMENT</div>
        <div class="ocr-section-content">
          <div class="document-row">
            <Tag
              v-if="data.receipt_type"
              :value="data.receipt_type === 'bon_fiscal' ? 'Bon Fiscal' : 'Chitanta'"
              :severity="data.receipt_type === 'bon_fiscal' ? 'info' : 'success'"
            />
            <span v-if="data.receipt_number" class="doc-number">
              Nr: {{ data.receipt_series ? data.receipt_series + ' ' : '' }}{{ data.receipt_number }}
            </span>
            <span v-if="data.receipt_date" class="doc-date">
              <i class="pi pi-calendar"></i>
              {{ formatDate(data.receipt_date) }}
              <OCRConfidenceIndicator :confidence="data.confidence_date" size="small" />
            </span>
          </div>
        </div>
      </div>

      <!-- SECTION: TOTAL + PLATA + TVA (unified flat layout) -->
      <div class="ocr-section" v-if="data.amount || data.tva_entries?.length > 0 || paymentSum > 0">
        <div class="ocr-values-table">
          <!-- TOTAL row - when extracted -->
          <div class="value-row" v-if="data.amount">
            <span class="value-label">TOTAL</span>
            <span class="value-amount">
              {{ formatAmount(data.amount) }} LEI
              <OCRConfidenceIndicator :confidence="data.confidence_amount" size="small" class="confidence-inline" />
            </span>
          </div>

          <!-- TOTAL row - warning when not found but can be calculated from payments -->
          <div class="value-row warning-row" v-else-if="paymentSum > 0">
            <span class="value-label">
              <i class="pi pi-exclamation-triangle warning-icon"></i>
              TOTAL (calculat)
            </span>
            <span class="value-amount calculated">
              {{ formatAmount(paymentSum) }} LEI
              <span class="hint">(din plati)</span>
            </span>
          </div>

          <!-- Validation warning: total ≠ payment sum -->
          <div class="validation-warning" v-if="totalMismatchPayment">
            <i class="pi pi-exclamation-triangle"></i>
            Total ({{ formatAmount(data.amount) }}) ≠ Suma plati ({{ formatAmount(paymentSum) }})
          </div>

          <!-- Validation info: TVA-implied total mismatch -->
          <div class="validation-info" v-if="totalMismatchTva">
            <i class="pi pi-info-circle"></i>
            Total din TVA: {{ formatAmount(tvaImpliedTotal) }} LEI
          </div>

          <!-- Payment methods as plain text rows -->
          <div class="value-row" v-for="(pm, idx) in data.payment_methods" :key="'pm-'+idx">
            <span class="value-label">{{ pm.method }}</span>
            <span class="value-amount">{{ formatAmount(pm.amount) }} LEI</span>
          </div>

          <!-- TVA entries -->
          <div class="value-row" v-for="(entry, idx) in data.tva_entries" :key="'tva-'+idx">
            <span class="value-label">TVA {{ entry.code }} ({{ entry.percent }}%)</span>
            <span class="value-amount">{{ formatAmount(entry.amount) }} LEI</span>
          </div>

          <!-- TVA Total -->
          <div class="value-row total-row" v-if="computedTvaTotal > 0">
            <span class="value-label">Total TVA</span>
            <span class="value-amount">{{ formatAmount(computedTvaTotal) }} LEI</span>
          </div>

          <!-- Items count -->
          <div v-if="data.items_count" class="items-count-inline">
            {{ data.items_count }} articole
          </div>
        </div>
      </div>

      <!-- Raw Text Toggle -->
      <div class="raw-text-section" v-if="data.raw_text">
        <div class="raw-text-header">
          <Button
            :label="showRawText ? 'Ascunde text OCR' : 'Arata text OCR'"
            :icon="showRawText ? 'pi pi-eye-slash' : 'pi pi-eye'"
            severity="secondary"
            size="small"
            text
            @click="showRawText = !showRawText"
          />
          <span v-if="data.ocr_engine" class="ocr-engine-badge" :class="getEngineClass(data.ocr_engine)">
            <i :class="getEngineIcon(data.ocr_engine)"></i>
            {{ getEngineLabel(data.ocr_engine) }}
          </span>
          <span v-if="data._ocr_message" class="ocr-message-badge" :class="getMessageClass(data._ocr_message)">
            {{ data._ocr_message }}
          </span>
          <span v-if="data.processing_time_ms" class="ocr-time-badge">
            <i class="pi pi-clock"></i>
            {{ formatProcessingTime(data.processing_time_ms) }}
          </span>
        </div>
        <div v-if="showRawText" class="raw-text">
          <pre>{{ data.raw_text }}</pre>
        </div>
      </div>
    </div>

    <div class="preview-actions">
      <Button
        label="Ignora"
        icon="pi pi-times"
        severity="secondary"
        @click="$emit('dismiss')"
      />
      <Button
        label="Aplica datele in formular"
        icon="pi pi-check"
        @click="$emit('apply', data)"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import OCRConfidenceIndicator from './OCRConfidenceIndicator.vue'
import Tag from 'primevue/tag'
import Button from 'primevue/button'

const props = defineProps({
  data: {
    type: Object,
    required: true
  }
})

defineEmits(['apply', 'dismiss', 'collapse'])

const showRawText = ref(false)

// Computed TVA total from entries
const computedTvaTotal = computed(() => {
  if (props.data.tva_total) return parseFloat(props.data.tva_total)
  if (!props.data.tva_entries?.length) return 0
  return props.data.tva_entries.reduce((sum, e) => sum + parseFloat(e.amount || 0), 0)
})

// Cross-validation computed properties
const paymentSum = computed(() => {
  if (!props.data.payment_methods?.length) return 0
  return props.data.payment_methods.reduce((sum, pm) => sum + parseFloat(pm.amount || 0), 0)
})

const tvaImpliedTotal = computed(() => {
  // Calculate total from TVA: total = tva * (100 + rate) / rate
  if (!props.data.tva_entries?.length) return 0
  const mainEntry = props.data.tva_entries[0]
  const rate = mainEntry.percent || 19
  const tvaAmount = parseFloat(mainEntry.amount || 0)
  if (tvaAmount === 0 || rate === 0) return 0
  return tvaAmount * (100 + rate) / rate
})

const totalMismatchPayment = computed(() => {
  if (!props.data.amount || paymentSum.value === 0) return false
  const total = parseFloat(props.data.amount)
  return Math.abs(total - paymentSum.value) > 0.02  // Tolerance 2 bani
})

const totalMismatchTva = computed(() => {
  if (!props.data.amount || tvaImpliedTotal.value === 0) return false
  const total = parseFloat(props.data.amount)
  return Math.abs(total - tvaImpliedTotal.value) > 0.50  // Tolerance 50 bani (TVA calc has rounding)
})

const getSuggestedPaymentLabel = (mode) => {
  const labels = {
    'casa': 'Casa (numerar firma)',
    'banca': 'Banca (virament/POS)',
    'avans_decontare': 'Avans Decontare'
  }
  return labels[mode] || mode
}

const formatAmount = (amount) => {
  const num = parseFloat(amount)
  return num.toLocaleString('ro-RO', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('ro-RO', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
}

const getEngineClass = (engine) => {
  if (!engine) return ''
  // docTR engines
  if (engine === 'doctr-light') return 'doctr-fast'
  if (engine === 'doctr-medium') return 'doctr'
  if (engine === 'doctr-adaptive') return 'doctr-adaptive'
  if (engine.includes('doctr')) return 'doctr'
  // PaddleOCR engines
  if (engine === 'paddle-light') return 'fast'
  if (engine === 'paddle-adaptive') return 'adaptive'
  if (engine === 'adaptive-full') return 'full'
  if (engine.includes('paddle')) return 'paddleocr'
  if (engine.includes('tesseract')) return 'tesseract'
  return ''
}

const getEngineIcon = (engine) => {
  if (!engine) return 'pi pi-cog'
  // docTR - use bolt for fast modes
  if (engine === 'doctr-light') return 'pi pi-bolt'
  if (engine.includes('doctr')) return 'pi pi-bolt'
  // PaddleOCR
  if (engine === 'paddle-light') return 'pi pi-bolt'
  if (engine === 'adaptive-full') return 'pi pi-cog'
  return 'pi pi-cog'
}

const getEngineLabel = (engine) => {
  if (!engine) return ''
  // docTR engines
  if (engine === 'doctr-light') return 'docTR Fast'
  if (engine === 'doctr-medium') return 'docTR Medium'
  if (engine === 'doctr-adaptive') return 'docTR Adaptive'
  if (engine.includes('doctr')) return 'docTR'
  // PaddleOCR engines
  if (engine === 'paddle-light') return 'Fast Mode (PaddleOCR)'
  if (engine === 'paddle-adaptive') return 'Adaptive (Paddle dual)'
  if (engine === 'adaptive-full') return 'Full Pipeline'
  if (engine.includes('paddle')) return 'PaddleOCR'
  if (engine.includes('tesseract')) return 'Tesseract'
  return engine
}

const getMessageClass = (message) => {
  if (!message) return ''
  if (message.includes('fast mode')) return 'fast-mode'
  if (message.includes('full pipeline')) return 'full-pipeline'
  return ''
}

const formatProcessingTime = (ms) => {
  if (ms < 1000) return `${ms}ms`
  return `${(ms / 1000).toFixed(1)}s`
}
</script>

<style scoped>
.ocr-preview {
  background: var(--green-50);
  border: 1px solid var(--green-300);
  border-radius: 12px;
  margin: 1rem 0;
  overflow: hidden;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 1rem;
  background: var(--green-100);
  border-bottom: 1px solid var(--green-300);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.title {
  font-weight: 600;
  color: var(--green-800);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.overall-confidence {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.85rem;
  color: var(--green-800);
}

.collapse-btn {
  color: var(--green-800) !important;
}

.preview-content {
  padding: 0.75rem 1rem;
}

/* Section-based layout (bon fiscal style) - clearer separation */
.ocr-section {
  padding: 0.75rem;
  margin-bottom: 0.5rem;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 8px;
  border: 1px solid var(--green-200);
}

.ocr-section:last-of-type {
  margin-bottom: 0;
}

.ocr-section-title {
  font-size: 0.7rem;
  font-weight: 700;
  color: var(--green-800);
  text-transform: uppercase;
  letter-spacing: 0.08em;
  margin-bottom: 0.5rem;
  padding-bottom: 0.35rem;
  border-bottom: 1px dashed var(--green-300);
}

.ocr-section-content {
  color: var(--text-color);
}

/* FURNIZOR section */
.vendor-name {
  font-weight: 600;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.vendor-cui {
  font-size: 0.85rem;
  color: var(--text-color-secondary);
  margin-top: 0.15rem;
}

.vendor-address {
  font-size: 0.8rem;
  color: var(--text-color-secondary);
  margin-top: 0.15rem;
}

/* CLIENT section */
.client-name {
  font-weight: 600;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.client-cui {
  font-size: 0.85rem;
  color: var(--text-color-secondary);
  margin-top: 0.15rem;
}

.client-address {
  font-size: 0.8rem;
  color: var(--text-color-secondary);
  margin-top: 0.15rem;
}

/* Placeholder when no data extracted */
.no-data {
  color: var(--text-color-secondary);
  font-style: italic;
}

/* DOCUMENT section */
.document-row {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-wrap: wrap;
}

.doc-number {
  font-weight: 500;
  color: var(--text-color);
}

.doc-date {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  color: var(--text-color-secondary);
  font-size: 0.9rem;
}

.doc-date .pi-calendar {
  font-size: 0.85rem;
  color: var(--text-color-secondary);
}

/* Unified values table (TOTAL + Payment + TVA) */
.ocr-values-table {
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
}

.value-row {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  padding: 0.25rem 0;
}

.value-label {
  font-weight: 500;
  color: var(--text-color);
}

.value-amount {
  font-weight: 600;
  margin-left: auto;
  color: var(--text-color);
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.value-row.total-row {
  margin-top: 0.35rem;
  padding-top: 0.5rem;
  border-top: 1px dashed var(--green-300);
}

/* Items count - subtle, at bottom of values section */
.items-count-inline {
  font-size: 0.8rem;
  color: var(--text-color-secondary);
  text-align: right;
  padding-top: 0.35rem;
}

/* Confidence indicator inline */
.confidence-inline {
  margin-left: 0.25rem;
}

/* Warning row for calculated total */
.value-row.warning-row {
  background: var(--yellow-100);
  border-radius: 6px;
  padding: 0.5rem 0.75rem;
  margin: 0.25rem 0;
}

.value-row.warning-row .value-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: var(--yellow-800);
}

.warning-icon {
  color: var(--yellow-500);
  font-size: 0.9rem;
}

.value-amount.calculated {
  color: var(--yellow-800);
}

.value-amount .hint {
  font-size: 0.75rem;
  font-weight: 400;
  color: var(--text-color-secondary);
}

/* Validation warnings */
.validation-warning {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  margin: 0.25rem 0;
  background: var(--red-100);
  border-radius: 6px;
  font-size: 0.8rem;
  color: var(--red-800);
}

.validation-warning i {
  color: var(--red-600);
  font-size: 0.9rem;
}

/* Validation info */
.validation-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  margin: 0.25rem 0;
  background: var(--blue-100);
  border-radius: 6px;
  font-size: 0.8rem;
  color: var(--blue-700);
}

.validation-info i {
  color: var(--blue-600);
  font-size: 0.9rem;
}

.raw-text-section {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px dashed var(--green-300);
}

.raw-text-header {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.75rem;
}

.ocr-engine-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
}

.ocr-engine-badge.paddleocr {
  background: var(--blue-100);
  color: var(--blue-700);
}

.ocr-engine-badge.tesseract {
  background: var(--yellow-100);
  color: var(--yellow-800);
}

.ocr-engine-badge.fast {
  background: var(--green-100);
  color: var(--green-800);
}

.ocr-engine-badge.adaptive {
  background: var(--blue-100);
  color: var(--blue-700);
}

.ocr-engine-badge.full {
  background: var(--yellow-100);
  color: var(--yellow-800);
}

/* docTR engine styles */
.ocr-engine-badge.doctr {
  background: var(--purple-100);
  color: var(--purple-700);
}

.ocr-engine-badge.doctr-fast {
  background: var(--teal-100);
  color: var(--teal-700);
}

.ocr-engine-badge.doctr-adaptive {
  background: var(--indigo-100);
  color: var(--indigo-700);
}

.ocr-message-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
  background: var(--surface-100);
  color: var(--text-color-secondary);
}

.ocr-message-badge.fast-mode {
  background: var(--green-100);
  color: var(--green-800);
}

.ocr-message-badge.full-pipeline {
  background: var(--yellow-100);
  color: var(--yellow-800);
}

.ocr-time-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 600;
  background: var(--indigo-100);
  color: var(--indigo-700);
}

.raw-text {
  margin-top: 0.5rem;
  padding: 0.75rem;
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: 8px;
  max-height: 200px;
  overflow: auto;
}

.raw-text pre {
  margin: 0;
  font-size: 0.75rem;
  white-space: pre-wrap;
  word-break: break-word;
  color: var(--text-color-secondary);
}

.preview-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  background: var(--surface-ground);
  border-top: 1px solid var(--surface-border);
}

@media (max-width: 640px) {
  .preview-header {
    flex-direction: column;
    gap: 0.5rem;
    align-items: flex-start;
  }

  .preview-grid {
    grid-template-columns: 1fr;
  }

  .preview-actions {
    flex-direction: column;
  }
  /* PrimeVue button width moved to vendor/primevue-overrides.css */
}
</style>
